hdu 3183 A Magic Lamp(RMQ)

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

HDU 2009-11 Programming Contest


题意:对于一个序列A[1...N],一共N个数,除去M个数使剩下的数组成的整数最小。

思路:

对于序列A[1...N],选取N-M个数,使组成的值最小,而且顺序不能交换,既然要选取N-M个,那么可以容易知道这N-M位数的第一位一定在数组A中的区间

[1M+1]中出现,为什么是这样呢?

我们可以这样来模拟一下:假设A数组就只有6个数,分别是A[1]A[2]A[3]A[4]A[5]A[6],我们去掉M=2个数,使形成的值最小。

那么我们此时的N=6,M=2N-M=4

则我们说形成的4位数的第一位一定在区间[13]中出现,因为如果区间范围再大点,比如[14],这样就不科学了,因为第一位一定不会是A[4],更不会是

A[5]A[6],我们假设可以是A[4],那么后面只有A[5]A[6]两位数了,这样的话最多只可能形成3位数,绝对不能形成N-M=4位了。

当然到了这里,我们就可以这样做了,第一位可以在区间[1M+1]里面找,假设第一位在位置x,因为第二位肯定在第一位的后面,所以第二位一定存在于

区间[x+1M+2],为什么是M+2,因为第一位已经确定了,现在只需要确定N-M-1位了,所以区间就可以向后增加1,一直这样循环下去,就可以找到了。

需要注意的是dp[i][j]求的是i到i+(1<<j)-1的值最小的下标;


代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int N=1005;
char c[N];
int dp[N][20];
char a[N];
int minn(int x,int y)
{
    return c[x]<=c[y]?x:y;
}
void make_rmq(int n)
{
    for(int i=0;i<n;i++)
        dp[i][0]=i;
    for(int j=1;(1<<j)<n;j++)
        for(int i=0;i+(1<<j)-1<n;i++)
            dp[i][j]=minn(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
}
int query(int l,int r)
{
    int n=(int)(log(r-l+1.0)/log(2.0));
    return minn(dp[l][n],dp[r-(1<<n)+1][n]);
}
int main()
{
    while(~scanf("%s",c))
    {
        int n,m;
        scanf("%d",&m);
        n=strlen(c);
        make_rmq(n);
        int temp=0,mm=m;
        for(int i=1;i<=n-m;i++)
        {
            temp=query(temp,mm);
            mm++;
            a[i]=c[temp++];
        }
        int flag=0;
        for(int i=1;i<=n-m;i++)
        {
            if(a[i]=='0'&&!flag)
                continue;
            else
            {
                printf("%c",a[i]);
                flag=1;
            }
        }
        if(!flag)
            printf("0");
        printf("\n");
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值