【每日一题】Problem 489C. Given Length and Sum of Digits...
解决思路
结果值越大,要求满足后续数位能成立的情况下,当前数位的值尽可能大;取最小结果同理
误区
- 注意边界
- 一般情况下,数字开头不能为 0,除非数字长度为 1
- 任意数位的最大值不超过 9,不低于 0 或 1
- m 的最大长度为 100,因此无法用数值类型来表示,可以考虑用 stringstream 来避免麻烦的字符串拼接过程
#include <bits/stdc++.h>
int main() {
int m, s; std::cin >> m >> s;
std::stringstream ssh, ssl;
if (m == 1) {
ssh << (s > 9 ? -1 : s);
ssl << (s > 9 ? -1 : s);
} else {
if (s > 9 * m || s == 0) ssh << -1, ssl << -1;
else {
int hcur, lcur; hcur = lcur = 0;
int hs, ls; hs = ls = s;
for (int i = 1; i <= m; ++i) {
hcur = std::min(hs, 9);
ssh << hcur;
hs -= hcur;
lcur = i == 1 ? 1 : 0;
lcur = std::max(ls - 9 * (m - i), lcur);
ssl << lcur;
ls -= lcur;
}
}
}
std::string ansh, ansl;
ssh >> ansh, ssl >> ansl;
std::cout << ansl << " " << ansh << "\n";
return 0;
}
本文来自博客园,作者:HelloEricy,转载请注明原文链接:https://www.cnblogs.com/HelloEricy/p/17515363.html