题目描述
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.
翻译:给你一些数字片段的集合,你需要根据它们恢复最小的数字。举个例子,给你 {32, 321, 3214, 0229, 87}, 我们根据这些片段的不同排列组合恢复成许多数像 32-321-3214-0229-87 或者 0229-32-87-321-3214,并且最小的数字是 0229-321-3214-32-87。
INPUT FORMAT
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.
翻译:每个输入文件包含一组测试数据。对于每组输入数据,第一个为正整数N(<=10000) ,跟着N个数字片段。每个片段包括一个不超过8个数字的非负整数。所有一行内的数字都用空格隔开。
OUTPUT FORMAT
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,前三位都是相同的,那我们比较第四位就是3和4比较,因为321后跟的肯定是3开头的数字。同理,32和321则为321小。注意点:字符串前的所有前导0都要删掉,所以可以先将融合后的字符串保存起来,然后输出。如果删去前导0后字符串位数为0,则输出0。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#define INF 99999999
using namespace std;
vector<string> v;
int N;
bool cmp(string a,string b){
int al=a.size(),bl=b.size();
int length=max(al,bl);
char Ta,Tb;
for(int i=0;i<length;i++){
if(i>=al)Ta=a[0];
else Ta=a[i];
if(i>=bl)Tb=b[0];
else Tb=b[i];
if(Ta!=Tb)return Ta<Tb;
}
}
int main(){
scanf("%d",&N);
string s;
for(int i=0;i<N;i++){
cin>>s;
v.push_back(s);
}
sort(v.begin(),v.end(),cmp);
s="";
for(int i=0;i<v.size();i++)s+=v[i];
int flag=0;
for(int i=0;i<s.size();i++){
if(s[i]=='0'&&flag==0)continue;
if(s[i]!='0'&&flag==0)flag=1;
cout<<s[i];
}
if(flag==0)cout<<"0";
cout<<endl;
return 0;
}