博客
关于我
【笨方法学PAT】1038 Recover the Smallest Number (30 分)
阅读量:133 次
发布时间:2019-02-26

本文共 1148 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要将给定的数字段重新排列,使得组合起来的数最小。我们可以使用贪心算法来实现这一点。

方法思路

  • 问题分析:我们需要将给定的数字段重新排列,使得组合后的数最小。每个数字段可能包含前导零,因此在排列时需要特别注意。
  • 贪心算法:对于两个数字段a和b,我们需要决定a放在b前面还是后面,使得组合后的结果最小。我们可以比较a+b和b+a的大小,选择较小的顺序。
  • 排序:将所有数字段按照上述比较方式排序。
  • 连接和去除前导零:连接排序后的数字段,去掉前导零,得到最终结果。
  • 解决代码

    #include 
    #include
    #include
    #include
    using namespace std;bool cmp(string s1, string s2) { return s1 + s2 < s2 + s1;}int main() { int n; cin >> n; vector
    v(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } sort(v.begin(), v.end(), cmp); string s; for (int i = 0; i < n; ++i) { s += v[i]; } // 去掉前导零 int start = 0; while (start < s.length() && s[start] == '0') { ++start; } if (start == s.length()) { cout << 0 << endl; } else { for (; start < s.length(); ++start) { cout << s[start]; } cout << endl; } system("pause"); return 0;}

    代码解释

  • 读取输入:首先读取输入的数字段数量n,然后读取每个数字段。
  • 排序:使用自定义的比较函数对数字段进行排序,确保每次比较都能得到最小的组合。
  • 连接数字段:将排序后的数字段连接成一个字符串。
  • 去除前导零:去掉连接后的字符串前面的零,确保输出的结果没有前导零。如果所有字符都是零,输出0。
  • 这种方法确保了我们每一步都选择了最优的排列,从而得到最小的数。

    转载地址:http://wlaf.baihongyu.com/

    你可能感兴趣的文章
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm版本过高问题
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>
    npm错误Error: Cannot find module ‘postcss-loader‘
    查看>>
    npm,yarn,cnpm 的区别
    查看>>
    NPOI之Excel——合并单元格、设置样式、输入公式
    查看>>
    NPOI初级教程
    查看>>
    NPOI利用多任务模式分批写入多个Excel
    查看>>