UVA11491-Erasing ans Winning(贪心)
Accept: 799 Submit: 5753
Time Limit: 3000 mSec
Problem 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
Sample Input
3759
6 3
123123
7 4
1000000
0 0
Sample Output
79
323
100
题解:这个题贪心的思路很明显,但是不同的贪心策略在效率上差距很大(我的效率就很差),我的思路很直接,要保留d个,那么答案的最高位肯定是前d+1个数的最大值,找到之后删去它前面的,继续找,如果删到最后发现d还是大于0,就说明在已经找到的答案串中还需要继续删,就把答案串当作原始串继续删,最后输出即可。交上去虽然A了,但是用了770ms,然后我惊奇地发现大佬们都是0ms过,找了找题解,发现了很好的做法(orz),大家可以作为参考。
博客的链接如下:
https://www.cnblogs.com/zyb993963526/p/6354314.html
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int n, d; 6 7 int main() 8 { 9 //freopen("input.txt", "r", stdin); 10 while (~scanf("%d%d", &n, &d) && (n || d)) { 11 string num, ans = ""; 12 cin >> num; 13 14 bool flag = false; 15 int pos = 0, len = num.length(); 16 while (d) { 17 if (d >= len-pos) { 18 flag = true; 19 d -= len - pos; 20 num = ans; 21 continue; 22 } 23 char Max = 0; 24 int i, p; 25 for (i = pos; i < pos + d + 1 && i < len; i++) { 26 if (Max < num[i]) { 27 Max = num[i]; 28 p = i; 29 } 30 } 31 ans += num[p]; 32 d -= p - pos; 33 pos = p + 1; 34 } 35 36 if (!flag) ans += num.substr(pos, num.size() - pos); 37 cout << ans << endl; 38 } 39 return 0; 40 }