1038 Recover the Smallest Number (30分) sort-cmp妙用(用于使字符串序列最小)

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805449625288704

题意

给一堆字符串,组合,使得到的字符串最小

Sample Input:

5 32 321 3214 0229 87

Sample Output:

22932132143287

思路

啊啊啊啊啊,cmp函数写成return a + b < b + a;的形式,保证它排列按照能够组成的最小数字的形式排列。https://www.liuchuo.net/archives/2303

code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string num[10007];
bool cmp(string x,string y) {
    return x+y<y+x;//!!!!!!!
}
int main()
{
    int N; cin>>N;
    for(int i=0;i<N;++i) cin>>num[i];
    sort(num,num+N,cmp);
    int f=1;
    for(int i=0;i<N;++i)
    {
        for(int j=0;j<num[i].size();++j)
        {
            if(num[i][j]=='0' && f) continue;
            else {
                f=0;
                cout<<num[i][j];
            }
        }
    }
    if(f) cout<<0;
    return 0;
}
原文地址:https://www.cnblogs.com/liuyongliu/p/13543296.html