1038 Recover the Smallest Number (30分) (贪心 cmp牛比)

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 (≤) 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


 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 using namespace std;
 5 
 6 vector<string> v;
 7 bool cmp(string a, string b) {
 8     return a + b < b + a;
 9 }
10 
11 int main() {
12 #ifndef ONLINE_JUDGE
13     freopen("in.txt", "r", stdin);
14     freopen("out.txt", "w", stdout);
15 #endif // ONLINE_JUDGE
16     int n;
17     cin >> n;
18     for(int i = 0; i < n; i++) {
19         string s;
20         cin >> s;
21         v.push_back(s);
22     }
23     sort(v.begin(), v.end(), cmp);
24     string ans = "";
25     for(int i = 0; i < v.size(); i++)
26         ans += v[i];
27     while(*ans.begin() == '0') {
28         ans.erase(ans.begin());
29     }
30     if(ans == "") cout << 0;
31     else cout << ans;
32 
33     return 0;
34 }

 

posted @ 2020-10-29 21:08  Serein_MK  阅读(101)  评论(0)    收藏  举报