博客
关于我
【笨方法学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/

    你可能感兴趣的文章
    Nmap扫描教程之Nmap基础知识
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>