1. 程式人生 > >A Magic Lamp HDU - 3183 (ST表)

A Magic Lamp HDU - 3183 (ST表)

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? 

Input

There 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. 

Output

For 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
#include <bits/stdc++.h>

using namespace std;
char a[10005];
int num[1005];
int st[10005][20];
int ans[1100];
void ST(int n)
{
    for(int i=0;i<n;i++)
        st[i][0] = i;
    for(int j = 1;(1<<j)<=n;j++)
    {
        for(int i = 0;(i+(1<<j)-1) < n;i++)
        {
            int a = st[i][j-1];
            int b = st[i+(1<<(j-1))][j-1];
            if(num[a] <= num[b]) st[i][j] = a;
            else st[i][j] = b;
        }
    }
}


int f(int l,int r)
{
    int k=(int)(log(r-l+1.0)/log(2.0));
    int b=st[l][k];
    int c=st[r-(1<<k)+1][k];
    if(num[b]<=num[c]) return b;
    else return c;
}

int main()
{
    int n,i,j,m;
    while(scanf("%s%d",a,&n) != EOF)
    {
        int len;
        len = strlen(a);
        for(i=0;i<=len;i++)
            num[i] = a[i] - '0';
        ST(len);
        m = len - n;
        i = j = 0;
        while(m--)
        {
            i = f(i,len-m-1);
            ans[j++] = num[i++];
        }
        int f = 0;
        for(i=0; i<j; i++)
        {
            if(f == 0&&ans[i] == 0)
                continue;
            printf("%d",ans[i]);
            f = 1;
        }
        if(f==0) printf("0");
        printf("\n");
    }
    return 0;
}