题意分析:
(1)给出若干个整数片段,问按怎样的顺序组合这些片段,使得这些片段组合起来后的数最小,求出这个最小的数
(2)要确定这些片段的顺序,首先要明确的就是对于任意两个片段来说,确定其相对位置来说是很简单的,两个片段a、b,最直接的方法就是判断他们按两种方式连接后ab和ba的大小,如果这些片段都是字符串,那么ab和ba都是相同位数的,直接利用C++字符串比较即可
(3)按照(2)的排序规则,即可将原序列排序成最小的数
可能坑点:
(1)注意对于排序后的序列中前面若干个连续的“0”串要过滤掉
(2)第一个非零串的前导0也要过滤掉
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string a,string b)
{
string temp1=a,temp2=b;
temp1+=b,temp2+=a;
if(temp1<temp2)return true;
else return false;
}
int main()
{
int N,i=0;
cin>>N;
const int num=N;
string str[num];
while(i<N)
{
cin>>str[i];
i++;
}
sort(&str[0],&str[N],cmp);
int j=0;
while(atoi(str[j].c_str())==0&&j<N)j++;
cout<<atoi(str[j].c_str());
for(int i=j+1;i<N;i++)cout<<str[i];
cout<<endl;
return 0;
}