单词积累
recover 恢复;弥补;重新获得
题目
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 (≤104) 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函数的使用,对str1和str2的排序,与其详细的指定规则,不如直接str1+str2和str2+str1大小比较返回,非常巧妙啊!
此外,还要注意,组合形成的数首位不能为0。
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10003;
string num[maxn];
bool cmp (string str1, string str2) {
return str1 + str2 < str2 + str1;
}
int main() {
int N;
cin>>N;
for (int i = 0; i < N; i++) {
cin>>num[i];
}
sort(num, num + N, cmp);
string ans;
for (int i = 0; i < N; i++) {
ans += num[i];
}
while(ans.size() != 0 && ans[0] == '0'){
ans.erase(ans.begin());
}
if(ans.size() == 0) printf("0\n");
else cout << ans<<endl;
}
网友评论