题目描述:
输入一个正整数数组,将它们连接起来排成一个数,输出能排出的所有数字中最小的一个。例如输入数组{32, 321},则输出这两个能排成的最小数字32132。请给出解决问题的算法,并证明该算法。
具体代码:
#include<vector>
#include<iostream>
#include<cstring>
using namespace std;
bool cmp (const int a,const int b); <span style="white-space:pre"> </span>//声明
int main(){
vector <int> num;
int n;
cin>>n;<span style="white-space:pre"> </span>//输入数组的大小
int d;
while(n--){cin>>d;num.push_back(d);}//输入每个数
sort(num.begin(),num.end(),cmp);<span style="white-space:pre"> </span>//调用sort函数排序
char a[100];
char b[1000]="\0";<span style="white-space:pre"> </span>//用以储存最终结果
for(int i=0;i<num.size();i++)
{itoa(num[i],a,10);
strcat(b,a);
cout<<a<<" ";
}
cout<<'\n';
cout<<b<<endl;
return 0;
}
bool cmp (const int a,const int b){
char c1[100],c2[100];
itoa(a,c1,10);
itoa(b,c2,10);
for(int i=0,j=0;c1[i]!='\0'||c2[i]!='\0';i++,j++){
if(c1[i]=='\0'&&c2[j]!='\0')i=0;
if(c1[i]!='\0'&&c2[j]=='\0')j=0;
if(c1[i]!=c2[j]){return(c1[i]<c2[j]);}
}
return false;
}