刪掉m爲後剩餘的數組成的數最小

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;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章