ACM_拼接数字

拼接数字

Time Limit: 2000/1000ms (Java/Others)

Problem Description:

给定一个正整数数组,现在把数组所有数字都拼接成一个大数字,如何使得拼接后的数字最小。

Input:

输入包含多组测试数据,每组数据首先输入一个整数n(1<=n<=10000),接下来有n个整数a[i](1<=a[i]<=10^5);

Output:

对于每组数据,输出拼接后最小的数字。

Sample Input:

3
3 32 321

Sample Output:

321323
解题思路:这道题中每个输入元素(最多6位)应看成字符串来处理,可以用vector来保存字符串。要使拼接得到的数字最小,应该遵循x+y<y+x的排序规则,最后直接输出元素即可。
AC代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 bool cmp(string x,string y){
 4     return x+y<y+x;
 5 }
 6 int main()
 7 {
 8     int n;vector<string> vec;char a[6];
 9     while(cin>>n){
10         vec.clear();
11         for(int i=0;i<n;++i){
12             cin>>a;vec.push_back(a);
13         }
14         sort(vec.begin(),vec.end(),cmp);
15         for(int i=0;i<n;++i)
16             cout<<vec[i];
17         cout<<endl;
18     }
19     return 0;
20 }

猜你喜欢

转载自www.cnblogs.com/acgoto/p/9027411.html