題目大意:給出n(n<=50)個數字,n個數字按某種順序連接,要求最終得到的數字最大。
由于不論怎么連接,最終得到數字的長度總是相同的,所以比較大小的方式,相當于比較數字對應的字符串的字典序大小。于是可以把輸入中的n個數字看作字符串。
考慮只有兩個字符串的情況,設為a和b,結果要么是a+b,要么是b+a('+'表示字符串連接)。于是,如果a+b>b+a,那么a應該排在b的前面。所以只需要按照這種規則給n個字符串排序即可。
做這道題的時候不是在家,這臺電腦里面又沒有裝g++什么的,寫完代碼之后沒有編譯運行直接提交的,于是AC。
以下是我的代碼:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
using namespace std;
const int kMaxn(57);
bool cmp(const string &a,const string &b)
{
return (a+b>b+a);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
int n;
while(cin>>n && n)
{
string r[kMaxn];
for(int i=1;i<=n;i++)
cin>>r[i];
sort(r+1,r+n+1,cmp);
for(int i=1;i<=n;i++)
cout<<r[i];
cout<<endl;
}
return 0;
}
posted on 2011-05-20 11:32
lee1r 閱讀(897)
評論(0) 編輯 收藏 引用 所屬分類:
題目分類:排序