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 ( ≤ 1 0 4 ) N (≤10^4) N(≤104) followed by N N 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
Caution:
這道題想了好久都沒有比較好的思路,遂上網查了查,看到這個題解,真的一語驚醒夢中人。
下面是搬運的這句話:
直接字元串排序然後合并再去除前導0,但排序規則不是直接比較大小,而是若S1+S2<S2+S1則S1排在S2前
Solution:
// Talk is cheap, show me the code
// Created by Misdirection 2021-08-16 18:01:28
// All rights reserved.
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
bool cmp(string& s1, string& s2){
return s1 + s2 < s2 + s1;
}
int main(){
int n;
scanf("%d", &n);
string *nums = new string[n];
for(int i = 0; i < n; ++i) cin >> nums[i];
sort(nums, nums + n, cmp);
string ans = "";
for(int i = 0; i < n; ++i) ans += nums[i];
while(ans[0] == '0') ans = ans.substr(1, ans.length() - 1);
if(ans.length() == 0) ans = "0";
printf("%s\n", ans.c_str());
return 0;
}
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL6dGVNVTVq5keRpHW4Z0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLwYzM5cTZwUDMlljN2EmZ5gjM0QjZ4EDOkRDMyAzYmVzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)