#148-【贪心】删数

版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/83472998

Description

输入一个高精度的正整数 n(长度小于或等于 240 位),去掉其中任意 s 个数字后剩下的数字按原左右次序将组成一个新的正整数。编程对给定的 n 和 s,寻找一种方案,使得剩下的数字组成的新数最小。

Input

输入两行,第 1 行为 1 个正整数 n,第 2 行为 1 个整数 s。

Output

输出一行一个数,表示最后剩下的最小数。

Sample Input

178543
4

Sample Output

13

从下一步能得到的数中选择最小的数。

#include <iostream>
#include <string>

using namespace std;

string s, _next, temp;

bool comp(string a, string b) // 高精度的比较
{
	if (a.size() > b.size())
	{
		return true;
	}
	if (a.size() < b.size())
	{
		return false;
	}
	
	return a > b;
}

int main(void)
{
	int n, i;
	
	cin >> s;
	scanf("%d", &n);
	
	while (n--)
	{
		temp = s;
		temp.erase(0, 1);
		for (i = 1; i < s.size(); ++i)
		{
			_next = s; // 枚举下一步能得到的数
			_next.erase(i, 1);
			while ((_next.size() > 1) && (_next[0] == '0')) // 去除前导零(注意!很多人在这里被坑)
			{
				_next.erase(0, 1);
			}
			if (comp(temp, _next)) // 找到所有可能的数中的最小值
			{
				temp = _next;
			}
		}
		s = temp;
	}
	while ((s.size() > 1) && (s[0] == '0'))
	{
		s.erase(0, 1);
	}
	
	cout << s;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/83472998