HDU 3183 A Magic Lamp(贪心 or RMQ)
http://acm.hdu.edu.cn/showproblem.php?pid=3183
题意:
Kiki likes traveling. One day she finds a magic lamp, unfortunately the genie in the lamp is not so kind. Kiki must answer a question, and then the genie will realize one of her dreams.
The question is: give you an integer, you are allowed to delete exactly m digits. The left digits will form a new integer. You should make it minimum.
You are not allowed to change the order of the digits. Now can you help Kiki to realize her dream?
解法一:
首先考虑对于n个数字组成的数,只删除1位的情况。
比如176832,删除一位使得剩下的数值最小。结果是删除7而不是删除8所以可知并不总是删除最大的那个数字。
一种可行的贪心策略是:对于n位数构成的数删除m位,每次总是删除这样的a[i]:它是第一个a[i]>a[i+1]的数,如果不存在则就删除a[n]。
不能有前导0。
#include<bits/stdc++.h>
using namespace std;
const int maxn=1010;
int main()
{
int i,m,tmp1,tmp2;
string s;
while(cin>>s>>m)
{
if(s.length()==m)//坑点
{
printf("0\n");
}
else
{
for(i=0;i<s.length()-1;i++)
{
if(m==0)
break;
tmp1=s[i]-'0';
tmp2=s[i+1]-'0';
if(tmp1>tmp2)
{
s.erase(i,1);
//cout<<s<<"&&&"<<endl;
i=-1;
m--;
}
}//cout<<s<<"**"<<endl;
if(m)
{
s=s.substr(0,s.length()-m);
}//cout<<s<<"^^^"<<endl;
while(s.length()>1)
{//cout<<s<<" "<<s.length()<<endl;
if(s[0]=='0')
s.erase(0,1);
else
break;
}
cout<<s<<endl;
}
}
}