hdu 3183

来源:互联网 发布:isignature签章软件 编辑:程序博客网 时间:2024/06/06 00:08

A Magic Lamp

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


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 1100001 212345 254321 2
 

Sample Output
1310123321
 


这题是个很简单的贪心思想;

题意:给出一个不超过1000位的数,求删去m个数字以后形成的最小的数是多少。

分析:我们可以把题目转化为这样一个模型:从A[1]、A[2]、……、A[n] n个数中选出n-m个数,使得组成的数最小。 
一、使用RMQ,设原数字长为n,那么除去m个数字后还剩n-m个数字。 
(1)因为有n-m个数字,那么在1到m+1位置中最小的那个数字必是结果中的第一个数字,记录其位置为pos 
(2)然后从这个位置的下个位置pos+1开始到m+2位置的数字中最小的那个数字必定是结果中第二个数字,以此类推下去向后找。 
(3)为了保证数字最小,所以要保证高位最小,还要保证数字长度满足条件



#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int N = 1100;
char str[N];
int res[N], minsum[N][20];
void init();
void rmq();
int mmin(int l,int r);
int n;
int Min(int a,int b)
{
    return str[a]<=str[b]?a:b;
}


int main()
{
    int m;
    while(scanf("%s %d",str, &m)!=EOF)
    {
        n=strlen(str);
        init();
        rmq();
        m=n-m;
        int p=0, num=0;
        while(m--)
        {
            p=mmin(p,n-m-1);
            res[num++]=(str[p]-'0');
            p++;
        }
        int i;
        for(i=0;i<num;i++)
        {
            if(res[i]!=0)
            {
                break;
            }
        }
        if(i==num)
        {
            printf("0\n");
            continue;
        }
        for(;i<num;i++)
        {
            printf("%d",res[i]);
        }
        printf("\n");
    }
    return 0;
}


void init()
{
    for(int i=0;i<n;i++)
    {
        minsum[i][0]=i;
    }
    return ;
}


void rmq()
{
    int k=(int)(log(n*1.0)/log(2.0));
    for(int j=1;j<=k;j++)
    {
        for(int i=0;i+(1<<j)<=n;i++)
        {
            minsum[i][j]=Min(minsum[i][j-1],minsum[i+(1<<(j-1))][j-1]);
        }
    }
    return ;
}


int mmin(int l,int r)
{
    int k=(int)(log(r-l+1)*1.0/log(2.0));
    return Min(minsum[l][k],minsum[r-(1<<k)+1][k]);
}

0 0
原创粉丝点击