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 (<=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 87Sample Output:
22932132143287
思路:用sort自定义排序,ab和ba两个用strcmp比大小,例如5,32(532 >235),02,34(0235<3402)
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
struct node
{
char name[10];
}w[10010];
int cmp(node a, node b)
{
int la = strlen(a.name);
int lb = strlen(b.name);
char sa[22], sb[22];
int t = 0;
for(int i = 0; i < la; i++)
sa[t++] = a.name[i];
for(int i = 0; i < lb; i++)
sa[t++] = b.name[i];
sa[t] = 0;
t = 0;
for(int i = 0; i < lb; i++)
sb[t++] = b.name[i];
for(int i = 0; i < la; i++)
sb[t++] = a.name[i];
sb[t] = 0;
return strcmp(sa, sb) < 0;
}
char str[101000];
int t = 0;
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%s", w[i].name);
}
sort(w, w + n, cmp);
for(int i = 0; i < n; i++)
{
for(int j = 0; w[i].name[j]; j++)
str[t++] = w[i].name[j];
}
int f = 1;
for(int i = 0; i < t; i++)
{
if(str[i] != '0')
{
printf("%s\n", str + i);
f = 0;
break;
}
}
if(f) printf("0\n");
return 0;
}