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

    你可能感兴趣的文章
    Python str与bytes之间的转换
    查看>>
    Python subprocess ffmpeg
    查看>>
    python subprocess Permission denied Errno 13
    查看>>
    Python subprocess.call - 将变量添加到 subprocess.call
    查看>>
    Python Subprocess.Popen 从一个线程
    查看>>
    Python subprocess.Popen 作为 Windows 上的不同用户
    查看>>
    Python subprocess.Popen() 等待完成
    查看>>
    Python sum 二维列表中具有相同第一个值的元素
    查看>>
    Python Sympy模块NoConversion:收敛到根失败;请尝试n<;15或MaxSteps>;50
    查看>>
    python time模块
    查看>>
    Python Tkinter Multiple Windows 教程
    查看>>
    Python tkinter 中的多处理
    查看>>
    Python Tkinter 笔记本小部件
    查看>>
    python try except finally_Python3基础 try-except-finally 的简单示例
    查看>>
    Python tweepy写入到sqlite3 db
    查看>>
    Python TypeError:格式字符串的参数不足
    查看>>
    Python UI自动化测试Page Objects企业级实战
    查看>>
    Python UI自动化测试三方库扩展详解
    查看>>
    python谷歌翻译,2021年9月10日亲测可用,一次可以翻译十万,强烈star
    查看>>
    Python UI自动化测试数据驱动实战
    查看>>