1038 Recover the Smallest Number (30)(30 分)

时间:2022-09-06 14:39:37

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. Do not output leading zeros.

Sample Input:

5 32 321 3214 0229 87

Sample Output:

22932132143287



通过样例可以看到 321 3214 32的顺序 321是 3214子串,很明显应该321在前,大小比较上也是 321 < 3214,而32却在321和3214后面,因为32是3214子串,14明显比32小,323214 比321432大,
所以根据这个去排序,然后凑成一个串去掉前导0.
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
using namespace std;
string s[10000];
int n;
bool cmp(string a,string b){
    if(a.size() < b.size() && a == b.substr(0,a.size()))
    {
        return a < b.substr(a.size(),b.size());
    }
    else if(a.size() > b.size() && b == a.substr(0,b.size()))
    {
        return a.substr(b.size(),a.size()) < b;
    }
    else return a < b;
}
int main() {
    string str;
    scanf("%d",&n);
    for(int i = 0;i < n;i ++) {
        cin>>s[i];
    }
    sort(s,s + n,cmp);
    for(int i = 0;i < n;i ++)
        str += s[i];
    int i = 0;
    while(i < str.size() && str[i ++] == '0');
    i --;
    cout<<str.substr(i,str.size());
}