PAT 甲级 1038 Recover the Smallest Number (30 分) 贪心排序

题意:

给定n个字符串,只包含数字,用所有的字符串组成一个大的字符串,要求去掉前导零后字典序最小

思路:

经典贪心问题,

不是简单的按照字典序排序,因为两个字符串长度不同会影响他们组合后的字典序,

对于两个字符串s,t, 通过比较st  和  ts 的字典序,就能知道他们顺序了

 

#include<bits/stdc++.h>
#include<cstring>
#define FI first
#define SE second

using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int maxn = 1e4 + 7;
const int INF = 0x7f7f7f7f;

int n;
struct node {
    string s, t;
}a[maxn];
bool cmp(node a, node b) {
    string s1 = a.s + b.s;
    string s2 = b.s + a.s;
    return s1 < s2;
}

string solve(string s) {
    int t = 0, len = s.size();
    while(s[t] == '0' && t < len) t++;
    return s.substr(t, len-t);
}
int main() {
    cin >> n;
    for(int i = 1; i <= n; ++i) {
        cin >> a[i].s;
        a[i].t = solve(a[i].s);
    }
    sort(a+1, a+1+n, cmp);
    bool ok = false;
    for(int i = 1; i <= n; ++i) {
        if(ok) {
            cout << a[i].s;
        }
        else{
            cout << a[i].t;
            if(a[i].t.size() > 0) ok = true;
        }
    }
    if(!ok) cout << 0;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章