博客
关于我
【笨方法学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 error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>