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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值