【PAT甲级】1038 Recover the Smallest Number(贪心+排序)

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given { 32, 321, 3214, 0229, 87 }, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (≤10​4​​) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the smallest number in one line. Notice that the first digit must not be zero.

Sample Input:

5 32 321 3214 0229 87

Sample Output:

22932132143287

题目大意

给出一组数字,输出这组数字组成的最小数字,数字开头的0可以忽略

个人思路

这题是贪心的思路,把尽量能使组合成的数字小的数字放在前面,实质上就是对数字进行正确的排序,然后将排序后的数字组合输出即可,注意如果给出的数字序列全是0组成的,则要单独输出一个0。

数字全部用字符串存储,排序方法一开始我是想自己进行比较,就是从第一位开始如果出现某位数字不一样的则这位数字小的数字字符串小。如果数字字符串长短不一,则将较长数字长出来的第一位和相同部分的第一位进行比较,小的那一个字符串小,排序函数如下所示

bool cmp(string s1, string s2) {
    // 找到bug了 但是不好改 比如001 0010的情况就会出错 所以还是用简单的s1+s2 < s2+s1吧
    int len1 = int(s1.length()), len2 = int(s2.length());
    for (int i = 0, j = 0; i < len1 && j < len2; ) {
        if (s1[i] != s2[j]) return s1[i] < s2[j];
        i ++;
        j ++;
    }
    if (len1 < len2) {
        return s1[0] < s2[len1];
    }
    else if (len1 > len2) {
        return s1[len2] < s2[0];
    }
    return s1 < s2;
}

但是这样的排序函数会有一个样例过不了,检查了很久后找出来是001 0010这样的情况。

所以排序方式就换了,这里参考了柳神的排序方式非常简单【因为觉得要把上面检查出来的情况加进去实在是太复杂了】,排序函数如下所示

bool cmp(string s1, string s2) {
    return s1+s2 < s2+s1;
}

通过对两两组合之后的字符串进行大小比较,从而进行排序。

其他的就没什么了,注意最后的答案从第一位非0的数字开始输出。

实现代码

#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 100005;

bool cmp(string s1, string s2) {
    return s1+s2 < s2+s1;
}

int main() {
    // 输入
    int n;
    cin >> n;
    string ss[maxn];
    for (int i = 0; i < n; i ++) {
        cin >> ss[i];
    }
    // 排序
    sort(ss, ss+n, cmp);
    // 组合
    string ans = "";
    for (int i = 0; i < n; i ++) {
        ans += ss[i];
    }
    // 输出
    bool begin = false;
    for (int i = 0; i < ans.length(); i ++) {
        if (ans[i] != '0') begin = true;
        if (begin) cout << ans[i];
    }
    if (!begin) cout << 0;
    
    return 0;
}

总结

学习不息,继续加油

有时候自己真的会把题目想复杂,还是缺少经验啊,多写代码多写代码!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值