题目链接:gdu 1178
Problem Description:
给定一个正整数数组,现在把数组所有数字都拼接成一个大数字,如何使得拼接后的数字最小。
Input:
输入包含多组测试数据,每组数据首先输入一个整数n(1<=n<=10000),接下来有n个整数ai;
Output:
对于每组数据,输出拼接后最小的数字。
Sample Input:
3
3 32 321
Sample Output:
321323
思路:
其实就是拼接字符串,关键在于重载字符串的比较运算符。
bool cmp(string s1, string s2){
return (s1 + s2 < s2 + s1);
}
代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
vector<string> vec;
bool cmp(string s1, string s2){
return (s1 + s2 < s2 + s1);
}
int main(){
int n;
while(scanf("%d", &n) == 1){
vec.clear();
char s[7];
for(int i = 0; i < n; i++){
scanf("%s", s);
vec.push_back(s);
}
sort(vec.begin(), vec.end(), cmp);
for(int i = 0; i < n; i++)
cout << vec[i];
printf("\n");
}
return 0;
}