其他分享
首页 > 其他分享> > 1038 Recover the Smallest Number (30 分)

1038 Recover the Smallest Number (30 分)

作者:互联网

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given { 32, 321, 3214, 0229, 87 }, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:
Each input file contains one test case. Each case gives a positive integer N (≤10
4
) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:
For each test case, print the smallest number in one line. Notice that the first digit must not be zero.

Sample Input:

5 32 321 3214 0229 87

结尾无空行
Sample Output:

22932132143287

结尾无空行

一开始将题目想复杂了,我以为要先手写一个字典序排序然后再进行输出呢,是我多虑了,直接 sort 函数就行,条件是 a + b < b + a 这样就能让字典序靠前的放前面。

核心问题解决了,这题就没难度了

#include<iostream>
#include<bits/stdc++.h>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<deque>
#include<unordered_set>
#include<unordered_map>
#include<cctype>
#include<algorithm>
#include<stack>
using namespace std;
bool cmp(string a, string b) {
	return a + b < b + a;
}
int main() {
	vector<string> v;
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;
		v.push_back(s);
	}
	sort(v.begin(), v.end(), cmp);
	string s = "";
	for (int i = 0; i < v.size(); i++) {
		s += v[i];
	}
	while (s.length() != 0 && s[0] == '0') {
		s.erase(s.begin());
	}
	if (s.length() == 0) {
		cout << "0";
	} else {
		cout << s;
	}
	return 0;
}

标签:3214,include,321,32,number,1038,Smallest,Recover,87
来源: https://blog.csdn.net/weixin_45962741/article/details/121988535