1038 Recover the Smallest Number (30分)

真正地理解了cmp函数的意义。

bool cmp(string& a,string& b) {
    // 如果a+b<b+a 则把a排在b前面
    return a+b<b+a;
}

如果a+b<b+a 则把a排在b前面

这样就不用自己去实现了,自己实现有点麻烦。

这个题有一个数据点是全0,好几个数都是0,所以去掉前导0之后会没有输出,要特判。

附:

升序排序

bool cmp(int a, int b) {
    // 如果a小于b,就把a排在前边
    return a<b;
}

降序排序:

bool cmp(int a, int b) {
    // 如果a大于b,就把a排在前边
    return a>b;
}

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN=1e4+10;

string a[MAXN];

bool cmp(string& a,string& b) {
    // 如果a+b<b+a 则把a排在b前面
    return a+b<b+a;
}

int main() {
    
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt","r",stdin);
#endif

    int N;
    cin>>N;
    for (int i=0;i<N;i++) { cin>>a[i]; }
    sort(a,a+N,cmp);
    
    /*
    if (N) {
        int tmp=stoi(a[0]);
        bool f=false;
        if (tmp) cout<<tmp,f=true;
        for (int i=1;i<N;i++) {
            if (!tmp) { 
                int tmp2=stoi(a[i]);
                if (tmp2!=0) cout<<tmp2,f=true; 
            }
            else cout<<a[i];
        }
        if (!f) cout<<"0";
        cout<<endl;
    }
    */
    string ans;
    for (int i=0;i<N;i++) {
        ans+=a[i];
    }
    while (ans[0]=='0') ans.erase(ans.begin());
    if (ans.size()) cout<<ans<<endl;
    else cout<<"0"<<endl;
    /*
    string ans;
    for (int i=0;i<N;i++) {
        ans+=a[i];
    }
    while (ans[0]=='0') ans.erase(ans.begin());
    if (ans.size()) cout<<ans<<endl;
    else cout<<"0"<<endl;
    */
    return 0;
}
原文地址:https://www.cnblogs.com/xyqxyq/p/13021894.html