您的位置:首页 > 其它

HDOJ 3183 A Magic Lamp(贪心)

2015-11-16 09:47 260 查看


A Magic Lamp

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2528    Accepted Submission(s): 991


[align=left]Problem Description[/align]
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?

 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
For each case, output the minimum result you can get in one line.

If the result contains leading zero, ignore it.

 

[align=left]Sample Input[/align]

178543 4
1000001 1
100001 2
12345 2
54321 2

 

[align=left]Sample Output[/align]

13
1
0
123
321

 

题意: 给出一个数字,在这个数字中取出m个数,问剩下的数最小的结果是多少,不输出前导零。

题解:这个数的长度是strlen,那么含有前导零的结果长度是len=strlen-m。 那么它的第一个数一定是在[0,m]的区间中的最小数,最右的边界一定只能是m,因为除第一个数外,还要取出strlen-m-1个数。假设第一个数的位置是temp, 取第二个数的范围就一定是[temp+1,m+1] ........    以此类推在去除前导零就可以得到最小的数。

代码如下:

#include<cstdio>
#include<cstring>
char num[1010];
char ans[1010];
int main()
{
int i,temp,m,t,k;
while(scanf("%s%d",num,&m)!=EOF)
{
t=0; k=0;
int len=strlen(num)-m;
while(len--)
{
temp=t;
for(i=t;i<=m;++i)
{
if(num[temp]>num[i])
temp=i;
}
ans[k++]=num[temp];
m++;
t=temp+1;
}
i=0;
while(ans[i]=='0'&&i<k)//去除前导零
i++;
if(i==k)
printf("0\n");
else
{
for(;i<k;++i)
printf("%c",ans[i]);
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: