首页 > 技术文章 > PAT.Recover the smallest number(字符串排序,注意输出)

bianjunting 2020-05-24 22:35 原文

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


这题搞了我好久...老是有一组样例无法通过,原来是因为一组特殊样例。即,当最后组成的数字等于零时,直接输出零。
由于我是用字符串做的,然后只判断了第一个字符串的前导零,其余的一概没有判断直接输出。导致的...
教训还是粗心吧,要细心一点把每个点都想到。

这题思路其实挺好想的,就是字符串排序,然后按照顺序输出,但是排序的时候注意,由于是要将字符串组成数字,所以
例如121111和121的两个字符串,字典序毫无疑问是前者大于后者,但是组成数字的时候显然是前者做前缀数字更小,那我们
如何排序呢,把所有原字符串既做前缀又做后缀组成一个新的字符串,然后对所有字符串排序,此时问题迎刃而解。

看别人博客还有一种方法,直接定义一个排序函数,return a + b < b + a,即两个字符串中做前缀组成数字小的那个字符串
在前,这种方法实属风骚也容易想到,应该是正解,至于我的方法...
 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 vector <string> vec;
 8 
 9 int main() {
10     int n;
11     string s;
12     cin >> n;
13     for(int i = 0; i < n; i ++) {
14         cin >> s;
15         s += s;
16         vec.push_back(s);
17     }
18     sort(vec.begin(), vec.end());
19     string ans = "";
20     for(int i = 0; i < n; i ++) {
21         for(int j = 0; j < vec[i].size() / 2; j ++) {
22             ans += vec[i][j];
23         }
24     }
25     while(ans[0] == '0') {
26         ans.erase(ans.begin());
27     }
28     if(ans.size()) cout << ans << endl;
29     else cout << '0' << endl;
30     return 0;
31 }

 

 

 

 

推荐阅读