给你几个数字段,重新组合数字段成为一个数,要求找能组成的最小数
Sample Input:
5 32 321 3214 0229 87
Sample Output:
22932132143287
第一时间就想到sort,但普通string数组sort后 32 < 321 < 3214
看了柳婼的解析,在比较时候 return s1 + s2 < s2 + s1 就行了,也就是只看每两个数段组成的数大小,就像对数组排序一样,只不过这里每个单元都是一个数段
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
//5 32 321 3214 0229 87
using namespace std;
bool cmp(string s1, string s2)
{
return s1 + s2 < s2 + s1;
}
int main()
{
int n;
cin>>n;
vector<string>v;
for(int i = 0; i < n; i++)
{
string s;
cin>>s;
v.push_back(s);
}
sort(v.begin(), v.end(), cmp);
string ans_str = "";
for(auto c:v )
ans_str += c;
while(ans_str.size() > 0 && ans_str[0] == ‘0‘)
ans_str.erase(ans_str.begin());
if(ans_str.size() == 0)
cout<<0;
else
cout<<ans_str;
}
PAT-甲级-1038 Recover the Smallest Number
原文:https://www.cnblogs.com/liushz-blog/p/14586460.html