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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章