HDU 3183 A Magic Lamp(RMQ)

本文介绍了一种通过删除指定数量的数字来构造最小数值的有效算法。该算法利用预处理技术加速查询过程,确保找到最佳数字组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给定一串全是数字的字符,问你删除m个数字之后的最小值是多少

思路因为要找n-m个数,删除m个数。所以原数的第1位到m+1位的数字中最小的那位(假设是第i位)肯定是n-m位数的第一位。(想想为什么)

        这样我们就找到了第一位a[i],接下来我们在从第i+1位数到m+2位数中找最小的那位,这个肯定是n-m位数的第二位。 为什么呢,如果我们原来串有6个数字,要删除2位,保留4位的话,对于第一位,我们在第1位到第3位选一个,如果我们从第1位到第四位选一个,我选第四个,那么剩下的只有5和6位就组不成4位数了。

        以此类推,找够n-m位即可。

          RMQ函数要做点修改。dmin[i][j]=k表示的是区间[ii+(1<<j)-1]内最小值的下标而不是值了。

        具体看下面代码.


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAXN=1000+100;
char a[MAXN];//初始字符数组
int ans[MAXN];//最后结果
int dmin[MAXN][20];
int minc(int i,int j)
{
    if(a[i]<=a[j])return i;
    return j;
}
void initMin(int n)
{
    for(int i=0; i<n; i++)dmin[i][0]=i;
    for(int j=1; (1<<j)<=n; j++)
        for(int i=0; i+(1<<j)-1<n; i++)
            dmin[i][j]=minc(dmin[i][j-1],dmin[i+(1<<(j-1))][j-1]);
}
int getMin(int L,int R)
{
    int k=0;
    while((1<<(k+1))<=R-L+1)k++;
    return minc(dmin[L][k] , dmin[R-(1<<k)+1][k]);
}
int main()
{
    int m;
    while(scanf("%s%d",a,&m)==2)
    {
        int n=strlen(a);
        int p=-1;
        initMin(n);
        for(int i=1; i<=n-m; i++)
        {
            p=getMin(p+1,m+i-1);//最终结果n-m位数的 第i个数的位置
            ans[i]=a[p]-'0';//最终结果n-m位数的 第i个数的值
        }
        int i;
        for(i=1; i<=n-m; i++)if(ans[i]!=0)break;
        if(i>n-m)printf("0\n");
        else
        {
            for(; i<=n-m; i++)
            {
                printf("%d",ans[i]);
            }
            printf("\n");
        }
    }
    return 0;
}

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
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值