题目大意:给你一个N位数字,让你删除其中的D位,使得剩下的数字最大。
思路:这道题是一道贪心题,一开始自己的贪心思想是这样的,使用一个结构体保存原本的位置和数字,读完后排次序消除前D个最小值,再根据结构体中储存的位置排序,然后输出,但是WA,最后发现自己的贪心思想是有错误的,我们如果想保证剩下的数是最大的,那么我们必须保证第一位是最大的,而后是第二位,那么最理想的数字,应该是从左到右数字大小依次减小,这让我想起了前不久学的单调栈(单调栈详解),于是便根据此进行贪心,然后AC。
下面给出AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+100;
const int INF=0x3f3f3f3f;
int n,m;
char c[maxn],t[maxn],ch;
stack<char> s;
int main()
{
//ios::sync_with_stdio(false);
while(scanf("%d %d",&n,&m)!=EOF)
{
if(n==0) break;
int len=n-m;
memset(c,0,sizeof(c));
for(int i=0; i<n; i++)
{
scanf(" %c",&ch);
while(m&&!s.empty())
{
if(s.top()<ch)
{
s.pop();
m--;
}
else break;
}
if(s.size()<len) s.push(ch);
else m--;
}
int pos=0;
while(!s.empty()) t[pos++]=s.top(),s.pop();
for(int i=pos-1;i>=0;i--) printf("%c",t[i]);
printf("\n");
}
return 0;
}