问题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805449625288704
Note:
- 如果把这些数字串按字典序从小到大排序,然后顺序输出,会出现出现错误: 如{”32“,”321“}按字典序排序是”32321“,但按题意,更小的答案是”32132“。
- 按题意正确的贪心策略是:对数字串S1和S2,如果S1+S2 < S2+S1,则把S1放到S2前面,否则把S2放到S1前面。
- 特别注意学习这个cmp函数排序!!!
题意:
给出若干可能有前导零的数字串,将它们按某个顺序拼接,使生成的数最小。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 10010;
string str[maxn];
bool cmp(string a, string b){
return a+b < b+a;//如果a+b < b+a
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> str[i];
sort(str, str+n, cmp);
string ans; //结果字符串
for(int i = 0; i < n; i++)
ans += str[i];// 将排序后的数字串进行拼接
while(ans.size() > 1 && ans[0] == '0')
ans.erase(ans.begin());
cout << ans;
return 0;
}