hdu3183—A Magic Lamp(RMQ,贪心)

来源:互联网 发布:md5加密c语言代码 编辑:程序博客网 时间:2024/06/05 03:00

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3183

A Magic Lamp

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


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
 

题目大意:给你一个很长的数字,去掉其中的m个数位,求重新获得数字的最小值

解题思路:RMQ+贪心

给出一串长度为L的数字,去掉其中的m个数字,也就是要从中取得(L-m)个数字,取第一个数字,从区间[1,m+1]取一个最小的数字,可以使得最终取得的数最小,因为这是取得的数的第一位,而剩下的(L-m-1)的数都可以在区间[m+2,L]全部取得,找到第一个最小的数所在位置t,则第二个数在区间[t+1,m+2]取最小值,依次取完m个数,得到是最终数的最小值。然后问题又变成了如何快速求得一个区间内的最小值,这里用个RMQ就可以了。


#include <cstdio>  #include <cstring>  #include <cmath>  #include <iostream>  #include <queue>#include <set>#include <string>#include <stack>#include <algorithm>#include <map>using namespace std;  typedef  long long ll;const int N = 1008;const int M = 20;const int INF = 0x3fffffff;const double Pi = acos(-1.0);int data[N];int dp[N][10];void RMQ( int n ){for( int i = 1 ; i <= n ; ++i ) dp[i][0] = data[i];for( int i = 1 ; (1<<i) <= n ; ++i ){for( int j = 1 ; j+(1<<i)-1 <= n ; ++j ){dp[j][i] = min( dp[j][i-1] , dp[j+(1<<(i-1))][i-1] );}}}int getValue( int l , int r ){int k = 0;while( (1<<(k+1)) <= r-l+1 ) k++;return min( dp[l][k] , dp[r-(1<<k)+1][k] );}int main(){string str;int n,cnt;while( cin>>str>>n ){cnt = 0;int len = str.length();for( int i = 0 ; i < len ; ++i ){data[i+1] = str[i]-'0';if( str[i] == '0' ) ++cnt;}if( cnt >= len-n){ cout << 0 << endl; continue; }RMQ( len );int l = 1,r = n+1;char st[N];for( int i = 0 ; i < len-n ; ++i ){int s = getValue( l , r );st[i] = s+'0';for( int j = l ; j <= r ; ++j ){if( data[j] == s ) { l = j+1; break; }}r = r+1;}st[len-n] = '\0';int k = 0;while( st[k] == '0' ) ++k;cout << st+k << endl;}return 0;}


原创粉丝点击