题目描述
设有nn个正整数(n≤20)(n≤20),将它们联接成一排,组成一个最大的多位整数。
例如:n=3n=3时,33个整数1313,312312,343343联接成的最大整数为:3433121334331213
又如:n=4n=4时,44个整数77,1313,44,246246联接成的最大整数为:74246137424613
输入格式
第一行,一个正整数nn。
第二行,nn个正整数。
输出格式
一个正整数,表示最大的整数
输入输出样例
输入 #1复制
3 13 312 343
输出 #1复制
34331213
分析:
这题没有那么复杂,但是要想明白,最容易想到的就是哪个数大哪个数排前面,但其实这是错的,因为前面要尽量大,比如132,17,明显应该17132,其次就是会想到判断第一位最大的那个在前面,若相等看第二位,以此类推...博主就是这么想的,但是会发现有一个数据WA了,给大家两个数据,如果能得出正确结论,应该就能AC了,第一个:30,300,正确应该是30300,第二个:13,135,正确应该是13513,不能只判断前面的位数,而是要综合评判来看
看题解有大神用string来存数,然后判断str1+str2<str2+str1,这是个很巧妙的方法,因为string的大小是根据ASCII编码的大小来的,刚好符合这道题的情况,处理好这一点,其他的就很简单了,上AC代码
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
typedef struct Shu{
int num;
}shu;
shu s[25];
int n;
bool cmp(Shu s1,Shu s2);
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>s[i].num;
sort(s+1,s+1+n,cmp);
for(int i=1;i<=n;i++)
cout<<s[i].num;
return 0;
}
bool cmp(Shu s1,Shu s2)
{
stack<int> a,b;
int temp1=s1.num;
int temp2=s2.num;
while(temp1)
{
int yu=temp1%10;
temp1=temp1/10;
a.push(yu);
}
while(temp2)
{
int yu=temp2%10;
temp2=temp2/10;
b.push(yu);
}
string str1,str2;
while(!a.empty())
{
int t1=a.top();
str1+=t1+'0';
a.pop();
}
while(!b.empty())
{
int t2=b.top();
str2+=t2+'0';
b.pop();
}
if(str1+str2>str2+str1)
return true;
else
return false;
}