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 ?rst 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 23759
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 }
UVA11491-Erasing ans Winning(貪心)