PAT1038 Recover the Smallest Number (30)(贪心)

题意:

给出一些字符串,把他们拼接起来获得最小数字

要点:

就是贪心,比较字符串大小,如果其中一个是另一个的子串就比较一下它和另一个除去相同子串剩下的部分即可。我一开始想复杂了,一直在考虑前导0的问题,觉得如果前导0放在中间可能会更小,但其实是不可能的,因为放在前面总位数变少了,所以压根不用考虑这么复杂,直接排序一下最后处理一下就完事了。不过网上的代码想法非常巧妙,下面贴一下。

#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<sstream>
#include<functional>
#include<algorithm>
using namespace std;
const int INF = 0xfffff;
const int maxn = 1005;

vector<string> number;

/*bool cmp(string a, string b) {
	return a + b < b + a;
}*/

bool cmp(string &a, string &b) {
	if (a.length() < b.length()) {
		auto pos = b.find(a);
		if (pos != string::npos) {
			string temp = b.substr(a.length());
			return a<temp;
		}
	} else {
		auto pos = a.find(b);
		if (pos != string::npos) {
			string temp = a.substr(b.length());
			return temp < b;
		}
	}
	return a < b;
}

int main() {
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		string temp;
		cin >> temp;
		number.push_back(temp);
	}
	sort(number.begin(), number.end(), cmp);
	string s;
	for (int i = 0; i < n; i++) {
		s += number[i];
	}
	while (s.length() != 0 && s[0] == '0') {
		s.erase(s.begin());
	}
	if (s.length() == 0)
		cout << 0 << endl;
	else
		cout << s << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/seasonjoe/article/details/80042126
今日推荐