课课通 P187最大整数 NOIP提高组1998拼数

 本人水平有限,题解不到为处,请多多谅解

 本蒟蒻谢谢大家观看

题目传送门

题意如下:有n个正整数,将他们连在一起排成一排可以组成的一个最大的多位整数

 

输入样例:

3

13 312 343

输出样例:

34331213

法一:

 如果直接比较字符串大小会WA,为什么呢?

解释如下:有一个反例  ch1='31',ch2='312';按照直接比较大小的话,答案为:31231

实际上,答案为:31312;为什么会出现这种情况呢?请继续往下看:

我们正解应该为比较ch1+ch2与ch2+ch1;意思是比较连接字符串后字符大小;

令 temp1=ch1+ch2=31231  ,  temp2=ch2+ch1=31312  ; 

因为 temp1<temp2 即 strcmp(temp1,temp2)<0 就更新temp1;

若不理解以下代码,可观看博客:https://www.cnblogs.com/nlyzl/p/11267905.html

code :

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 char num[21][30],temp1[60],temp2[60];
 4 int n;
 5 int main()
 6 {
 7     cin>>n;
 8     for(int i=1;i<=n;i++)
 9     {
10         cin>>num[i];
11     }
12     //cin>>temp1>>temp2;
13     for(int i=1;i<=n;i++)
14     {
15         for(int j=i+1;j<=n;j++)
16         {
17             strcpy(temp1,num[i]);
18             strcpy(temp2,num[j]);
19             strcat(temp1,num[j]);
20             strcat(temp2,num[i]);
21             //cout<<" ans1= "<<temp1<<endl;
22         //    cout<<" ans2= "<<temp2<<endl;
23             if(strcmp(temp1,temp2)<0)
24             {
25                 strcpy(temp1,num[i]);
26                 strcpy(num[i],num[j]);
27                 strcpy(num[j],temp1);
28             }
29             //cout<<" temp1= "<<temp1<<endl;
30             //cout<<" temp2= "<<temp2<<endl;
31         }
32     }
33     for(int i=1;i<=n;i++)
34     cout<<num[i];
35 }

法二:

直接利用string 将其排好序最后直接输出

code:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,yzl;
 4 string a[100010],k,m,ans;
 5 inline int read(){
 6     int x=0,f=1;char ch=getchar();
 7     while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
 8     while(isdigit(ch)){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
 9     return x*f;
10 }
11 int main(){
12     n=read();
13     for(int i=1;i<=n;i++){
14         cin>>a[i];
15         //scanf("%s",a);
16     }
17     for(int i=1;i<=n;i++){
18         yzl=0;
19         for(int j=i+1;j<=n;j++){
20             if(a[i]+a[j]<a[j]+a[i]){
21                 swap(a[i],a[j]);
22 //                k=a[i]+a[j];
23 //                m=a[j]+a[i];
24 //                yzl=k.compare(m);
25 //                if(yzl>0&&j==n&&i==1)ans=k;
26 //                else if(yzl<=0&&j==n&&i==1)ans=m;
27                 //cout<<"m= "<<m<<" k= "<<k<<" i ="<<i<<" j= "<<j<<endl;
28             }
29         }
30     }
31     for(int i=1;i<=n;i++)cout<<a[i];
32     //cout<<ans<<endl;
33     //for(int i=1;i<=n;i++)cout<<a[i];//printf("%s",a);
34     return 0;
35 } 
原文地址:https://www.cnblogs.com/nlyzl/p/11270912.html