HDOJ 3183 A Magic Lamp



A Magic Lamp

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 989    Accepted Submission(s): 371


Problem Description
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
 

Source
 

Recommend
lcy
 

贪心+RMQ

在其中取出len-m,使得取出的len-m位的数最小....这个问题是贪心问题: 设给出的数是X[1..len]..当前一共要取出N = len-m 个数字..

第一次取出的是[1..len-N+1]中取了一个最小的数字,下标为pre.然后N--..第二次就从[pre+1..len-N+1]中取出最小的那个数字..这样一直取出len-m

 

其中求区间最小值时,可用线段树或RMQ实现..


#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

int dp[1111][22];
char a[1111];
int n;
int out[1111];

void RMQ_init()
{
    for(int i=1;i<=n;i++)
        dp[0]=i-1;
    for(int j=1;(1<<j)<=n;j++)
        for(int i=1;i+(1<<j)-1<=n;i++)
    {
        int m=(1<<(j-1))+i;
        if(a[dp[j-1]]>a[dp
[j-1]])
            dp[j]=dp
[j-1];
        else if(a[dp[j-1]]==a[dp
[j-1]])
            dp[j]=min(dp[j-1],dp
[j-1]);
        else if(a[dp[j-1]]<a[dp
[j-1]])
            dp[j]=dp[j-1];
    }
}

int RMQ(int l,int r)
{
    int k=0;
    while((1<<(k+1))<=r-l+1)   k++;
    if(a[dp[l][k]]>a[dp[r-(1<<k)+1][k]])
        return dp[r-(1<<k)+1][k];
    else if(a[dp[l][k]]==a[dp[r-(1<<k)+1][k]])
        return min(dp[l][k],dp[r-(1<<k)+1][k]);
    else //if(a[dp[l][k]]<a[dp[r-(1<<k)+1][k]])
        return dp[l][k];
}

int main()
{
    int t;
while(scanf("%s%d",a,&t)!=EOF)
{
    memset(dp,-1,sizeof(dp));
    memset(out,-1,sizeof(out));

    n=strlen(a);
    if(n==t)  {   printf("0\n"); continue;}
    RMQ_init();
    int m=n-t;
    int cur=0;
    int pre=1;
    while(m)
    {
        out[cur]=RMQ(pre,n-m+1);
        pre=out[cur]+2;
  //      cout<<pre<<endl;
        m--;cur++;
    }

 //   cout<<cur<<endl;
    int start=0;
    for(int i=0;i<cur;i++)
    {
        if(a[out]!='0')
        {
            start=i;
            break;
        }
        if(i==cur-1&&a[out]=='0')
            start=cur-1;
    }
    for(int i=start;i<cur;i++)
        printf("%c",a[out]);

    putchar(10);

}
    return 0;
}

posted @ 2013-06-21 22:09  码代码的猿猿  阅读(110)  评论(0编辑  收藏  举报