【每日一题】Problem 489C. Given Length and Sum of Digits...

发布时间 2023-06-29 22:22:04作者: HelloEricy

原题

解决思路

结果值越大,要求满足后续数位能成立的情况下,当前数位的值尽可能大;取最小结果同理

误区
  1. 注意边界
    • 一般情况下,数字开头不能为 0,除非数字长度为 1
    • 任意数位的最大值不超过 9,不低于 0 或 1
  2. 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;
}