A Magic Lamp HDU - 3183 RMQ

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? 
InputThere are several test cases. 
Each test case will contain an integer you are given (which may at most contains 1000 digits.) and the integer m (if the integer contains n digits, m will not bigger then n). The given integer will not contain leading zero. 
OutputFor each case, output the minimum result you can get in one line. 
If the result contains leading zero, ignore it. 
Sample Input
178543 4 
1000001 1
100001 2
12345 2
54321 2
Sample Output
13
1
0
123
321

去掉m個數 就是選len-m個數  然而不能選len-m個最小的就完事了 
所以這時候就要用一些技巧 讓每次確實是在一段區間內找最小值
找規律可以發現(len-m)個數中的第一位一定在區間【1,m+1】中出現
假設第一位在第x位 那麼第二位一定在[x+1,m+2]中出現 多麼神奇 自己就是想不到QAQ

#include<bits/stdc++.h>


using namespace std;
int mmin[1005][20];
int a[1005];
int cal(int x,int y)
{
    if(a[x]<=a[y])
    return x;
    else return y;
}
void RMQ(int n)
{
    for(int i=0;i<n;i++)
    mmin[i][0]=i;


    for(int j=1;j<20;j++)
    {
        for(int i=0;i+(1<<j)-1<n;i++)
        {
            //mmax[i][j]=max(mmax[i][j-1],mmax[i+(1<<(j-1))][j-1]);
            mmin[i][j]=cal(mmin[i][j-1],mmin[i+(1<<(j-1))][j-1]);
        }
    }
}
int query(int l,int r)
{
    int k=log((double)(r-l+1))/log(2.0);
    return cal(mmin[l][k],mmin[r-(1<<k)+1][k]);
}
int main()
{
    char s[1005];


    int m;
    while(scanf("%s%d",s,&m)!=-1)
    {
        memset(mmin,0,sizeof(mmin));
        for(int i=0;s[i]!='\0';i++)
        {
            a[i]=(int)(s[i]-'0');
        }
        int len=strlen(s);
        int n=len-m;
        RMQ(len);
        int ans[1005];
        int i=0,j=0;
        while(n--)
        {
           i=query(i,len-n-1);
           ans[j++]=a[i++];
        }
        for(i=0;i<j;i++)
        {
            if(ans[i]!=0)break;
        }
        if(j==i)cout<<"0"<<endl;
        else
        {
            while(i<j)
            printf("%d",ans[i]),i++;
            cout<<endl;
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章