题目链接:UVA 11491 - Erasing and Winning(考虑到UVA的访问不是很方便,这里就放个vjudge的链接吧)
题目
Description
Juliano is a fan of the TV show Erasing and Winning, where participants are selected in a draw and
receive money for taking part in the show.
In the show, the presenter writes a number of N digits in a board. The participant must then erase
exactly D digits from the number in the board; the number formed by the remaining digits is the value
of the money prize for the participant.
Juliano was at last selected to take part in the show, and asked you to write a program that, given
the number the presenter wrote in the board, and the number of digits Juliano must erase, determines
the highest value of the prize he can win.
Input
The input contains several test cases. The first line of a test case contains two integers N and D
(1 ≤ D < N ≤ 105
) indicating respectively the number of digits of the number the presenter wrote
in the board and the number of digits that must be erased. The next line contains the number the
presenter wrote; the number does not start with a zero.
The end of input is indicated by a line containing only two zeros, separated by a space.
Output
For each test case in the input your program must produce one single line in the output, containing
the highest prize Juliano can win.
Sample Input
4 2
3759
6 3
123123
7 4
1000000
0 0
Sample Output
79
323
100
题目分析
给你一串数,让你从中取一个包含 N − D N-D N−D个数的子串,使得子串的值最大,从数据规模上看,动规显然是不现实的,那么这里就需要贪心解决。由于子串的长度是一定的,那么我们应该尽可能使高位上的数字大。我们对原串中的数字一个一个地分析。每次拿出原串中下一个数,如果它比新串中前一位的数更大,说明把前一位删除换成它肯定会比原来大,由于从高位到低位考虑,所以贪心不会受后面低位的影响,然后继续向前比,直到前一位比它大为止。重复这个操作直到新串长度足够或已无法继续删除为止。上代码:
#include <cstdio>
#include <algorithm>
using namespace std;
#define maxn 100000+5
int n,d;
int s[maxn], f[maxn];
char c;
void solve()
{
scanf("\n");
for(int i = 1; i <= n; i++)
scanf("%c", &c), s[i] = c - '0';
int dex = 2, len = n - d, ndex = 1;
f[1] = s[1];
while(dex <= n && d > 0){
while(ndex > 0 && s[dex] > f[ndex] && d > 0)
ndex -= 1, d -= 1;
f[++ndex] = s[dex++];
}
for(int i = 1; i <= min(len, ndex); i++)
printf("%d",f[i]);
len -= ndex;
for(int i = 0; i < len; i++)
printf("%d",s[dex++]);
printf("\n");
}
int main()
{
while(scanf("%d%d",&n, &d), n && d)
solve();
}