HDU 3182 ——A Magic Lamp

版权声明:没什么好说的,版权声明呢 https://blog.csdn.net/weixin_43741224/article/details/87450521

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

题目分析

       题意很简单,给你一个字符串,在这个字符串中删除指定数量的字符,而且不改变字符串的字符之间的顺序,使得删除指定数量的字符后的字符串所构成的数最小。

       写这个题的时候首先想到的就是不可以暴力,要是枚举每一种情况的话,那应该会超时。为了找到这个题所需的算法,我手动计算了几组数据:798194 2 以及 127299 2 ,得到的答案分别是7194 和 1229 。 首先对于每一组数据,删除相同数量的字符后,这些数字的位数都是一样的,那么我们就要使得高位的字符为最小,那么对于798194这组数据,7和9比,7更小,所以没必要删除7,因为删除了7的话,这个字符串的最高位的字符值就变大了,然后我们比较第二位9和第三位8,因为第二位数大于第三位数,所以删除9的话可以让第二位数变得更小,这样是划算的,由于删除了某个位上的数,所以我们需要从头重新开始比较。

      综上,我们每次比较字符串中相邻的两个字符,如果高位上的字符(比如89中,8的位就是比9的位高)大于低位上的字符,那么就删除高位上的字符,这样可以让低位上更小的字符代替高位的字符。而由于删除某个字符串,所以我们需要再次从最高位开始重复相邻位之间的比较,直到删除指定数量的字符为止。

代码区

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<string>
#include<cstring>
using namespace std;
const int inf = 0x3f3f3f3f;
const int max3 = 1000 + 10;

int main()
{
	char str[max3];
	int n;
	while(~scanf("%s%d",str,&n))
	{
		const int len = strlen(str);
		int index = 0;
		for(int i = 0 ; i < len ; i++)
		{
			if (!n)
				break;
			if (str[i] == '\0' || i < 0 )continue;
			int k = i + 1;
			char order = str[k];
			while (order == '\0' && k < len)
				order = str[++k];

			if (k == len || str[i] > order)	//表示高位的数字大于低位的数字或者k = len说明字符串已经按升序排序,那么删除最后一个即可
			{
				str[i] = '\0';
				i = - 1;
				n--;
			}
		}
		bool ok = false;
		for(int i = 0  ; i < len ; i++)
		{
			if(str[i] != '\0')
			{
				if(str[i] != '0' || ok)
				{
					printf("%c", str[i]);
					ok = true;
				}
			}
		}
		if (!ok)
			printf("0");
		cout << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43741224/article/details/87450521