题意:你是一个电视节目的获奖嘉宾。主持人在黑板上写出一个n位整数(不以0开头),邀请你删除其中的d个数字,剩下的整数便是你所获得的奖品的价值。当然,你希望这个奖品价值尽量大。 1≤d<n≤105 (本段摘自《算法竞赛入门经典(第2版)》)
分析:
开始是认为是贪心,去寻找不下降序列,将序列的最后一个元素保留,但是这个想法是错的,过不了如下数据:6 3 121314,如果采用贪心得到的结果是234,但是正确答案是314。正确想法是单调栈,维护一个单调递减栈即可。
代码:
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
using namespace std;
const int maxn = 100000 + 5;
int cnt, n, d;
char s[maxn], ans[maxn];
stack< char > sta;
int main()
{
while (~scanf("%d%d", &n, &d), n || d)
{
cnt = 0;
scanf("%s", s);
for (int i = 0; i < n; ++i)
if (sta.empty())
sta.push(s[i]);
else
{
if (s[i] <= sta.top())
sta.push(s[i]);
else
{
while (!sta.empty() && d && sta.top() < s[i])
{
sta.pop();
--d;
}
sta.push(s[i]);
}
}
while (!sta.empty())
{
ans[cnt++] = sta.top();
sta.pop();
}
for (int i = cnt - 1; i >= d; --i)
printf("%c", ans[i]);
printf("\n");
}
return 0;
}