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 (≤10
4
) 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
题目大意就是用给定的数字组合出一个最小数字,并且最前面的0不能输出。
乍一看好像没啥难的,不就是个排序问题么?这还真就是个排序问题,不过不能只按照字典序来排,题目要求组合出最小数字,相当于组合成最小的字符串,这时候就体现出sort()函数第三个参数的强大之处了。sort()函数的前两个参数分别为待排序序列的起始位置和终止位置,默认按字典序排序,传入第三个参数可以自定义排序规则。按照题目要求我们应该按照组合后最小来排序。个人觉得这个题用字符串来做比较方便。将排好序后的各个字符串拼接成一个字符串,查找其中第一个不为0的字符,若找不到则说明为全0串,直接输出0即可;找到了就从第一个不为0的字符开始一直输出到最后即可。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool compare(string a, string b) {//按照拼接后最小排序
string x = a + b;
string y = b + a;
return x < y;
}
int main()
{
int n;
cin >> n;
string num[10001];
for (int i = 0; i < n; i++)
cin >> num[i];
sort(num, num + n, compare);
string result = "";
for (int i = 0; i < n; i++)
result = result + num[i];
int index = result.find_first_not_of("0");//查找第一个不为0的字符
if (index == -1) {//找不到,为全0串,输出0
cout << 0 << endl;
return 0;
}
result = result.substr(index);//找到了,提取从第一个不为0的字符到最后的子串输出
cout << result << endl;
return 0;
}