NBU1449-剔除数字(加强版) (贪心+线段树优化)
NBU1449---删除数字(加强版) (贪心+线段树优化)
Description
在给定的n个数字的数字串中,删除其中k(k< n)个数字后,剩下的数字按原次序组成一个新的正整数。请确定删除方案,使得剩下的数字组成的新正整数最大。
Input
输入一个由n个数字组成的正整数(1< n<=100000),再输入一个整数k(0<=k
< n),输入的数字保证没有前导0。
Output
输出删除k位后的最大整数
Sample Input
102 1
Sample Output
12
HINT
Source
很显然的贪心题,但是范围略大,搞个线段树来优化一下就可以了
/*************************************************************************
> File Name: nbu1449.cpp
> Author: ALex
> Mail: zchao1995@gmail.com
> Created Time: 2015年04月18日 星期六 20时20分32秒
************************************************************************/
#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#include <set>
#include <vector>
using namespace std;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;
static const int N = 100010;
string str, ans;
struct node
{
int l, r;
int num;
int pos;
}tree[N << 2];
void build(int p, int l, int r)
{
tree[p].l = l;
tree[p].r = r;
if (l == r)
{
tree[p].num = str[l - 1] - '0';
tree[p].pos = l;
return;
}
int mid = (l + r) >> 1;
build(p << 1, l, mid);
build(p << 1 | 1, mid + 1, r);
if (tree[p << 1].num >= tree[p << 1 | 1].num)
{
tree[p].num = tree[p << 1].num;
tree[p].pos = tree[p << 1].pos;
}
else if (tree[p << 1 | 1].num > tree[p << 1].num)
{
tree[p].num = tree[p << 1 | 1].num;
tree[p].pos = tree[p << 1 | 1].pos;
}
}
int num, pos;
void query(int p, int l, int r)
{
if (tree[p].l == l && r == tree[p].r)
{
if (num < tree[p].num)
{
num = tree[p].num;
pos = tree[p].pos;
}
else if (num == tree[p].num && tree[p].pos < pos)
{
pos = tree[p].pos;
}
return;
}
int mid = (tree[p].l + tree[p].r) >> 1;
if (r <= mid)
{
query(p << 1, l, r);
}
else if (l > mid)
{
query(p << 1 | 1, l, r);
}
else
{
query(p << 1, l, mid);
query(p << 1 | 1, mid + 1, r);
}
}
int main()
{
int k;
while (cin >> str >> k)
{
ans.clear();
int n = str.length();
build(1, 1, n);
int need = n - k;
int l = 1, r = k + 1;
while (need)
{
num = -1;
query(1, l, r);
--need;
l = pos + 1;
++r;
ans += num + '0';
}
ans += "\0";
cout << ans << endl;
}
return 0;
}