天天看点

[NOIP1998]连接多位数

看到这题觉得可以用字符串存储数字,然后用strcmp()排序下就可以秒杀了,然而在两个数字的比较中,如果一者是另一者的“子集”(比如32和321),这样比较就可能会出现问题,于是特殊情况特殊处理。顺便熟悉下cmp函数的编写,之前一直对其返回值模糊不清。

#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;

bool cmp(string n1, string n2)
{
	if (n1.length() == n2.length())
		return n1 < n2;
	string sum1 = n1+n2, sum2 = n2+n1;
	return atoi(sum1.c_str()) < atoi(sum2.c_str());
}

int main()
{
	string s;
	vector<string> num;
	int n;
	cin >> n;
	for (int i = 0; i < n; ++i) {
		cin >> s;
		num.push_back(s);
	}
	sort(num.begin(), num.end(), cmp);
	for (int i = n-1; i >= 0; --i)
		cout << num[i];
	cout << endl;
	return 0;
}