题目
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 (≤10000) 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
代码长度限制 16 KB
时间限制 200 ms
内存限制 64 MB
题意
给定由几个可能有前导零的数字串,将它们按某种顺序拼接,使生成的数最小
题解
主要考察字符串的处理。本题如果使用二维数组来求解可能在编写排序函数sort和处理前导零时会比较麻烦,所以优先考虑使用string来处理字符串。
注意:
- 编写sort函数时需注意并不是a<b就把a放在前面,而是比较拼接后a+b和b+a的大小才决定a和b哪个放在前面。这种排序方法是最为简便的,然而这一点往往是比较难想到的。
- 结果串的所有前导0都要去掉,用while循环实现,如果所有字符都为0,则去除后串的大小为零,此时要输出0
代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string a, string b)
{
return a + b < b + a;
}
int main()
{
int n;
string num[10010];
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') //用循环去除前导0
ans.erase(ans.begin());
if(ans.size() == 0) cout << 0; //全为0则输出0
else cout << ans;
return 0;
}