fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<ll, ll> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. ll max_time;
  12. vector<int> digit;
  13.  
  14. vector<int> getDigit(ll n) {
  15. vector<int> ans;
  16. for (; n > 0; n /= 10) ans.push_back(n % 10);
  17. return ans;
  18. }
  19.  
  20. // dp = {tổng số lượng số target_digit, số lượng số}
  21. ii memo[19][2][2];
  22.  
  23. ii dp(int idx, bool leading, bool smaller, int target_digit) {
  24. if (idx == -1) return {0, 1};
  25.  
  26. ii& ans = memo[idx][leading][smaller];
  27. if (ans.first != -1) return ans;
  28.  
  29. ans = {0, 0};
  30. int max_digit = (smaller) ? 9 : digit[idx];
  31.  
  32. for (int i = 0; i <= max_digit; i++) {
  33. bool new_leading = leading & (i == 0);
  34. ii next_ans = dp(idx - 1, new_leading, smaller | (i < digit[idx]), target_digit);
  35. ans.first += next_ans.first + (!new_leading && i == target_digit) * next_ans.second;
  36. ans.second += next_ans.second;
  37. }
  38.  
  39. return ans;
  40. }
  41.  
  42. bool check(ll mid) {
  43. digit = getDigit(mid);
  44.  
  45. for (int target_digit = 0; target_digit <= 9; target_digit++) {
  46. memset(memo, -1, sizeof memo);
  47. ll cnt = dp(digit.size() - 1, 1, 0, target_digit).first;
  48. if (cnt > max_time) return false;
  49. }
  50.  
  51. return true;
  52. }
  53.  
  54. int main() {
  55. ios::sync_with_stdio(false);
  56. cin.tie(nullptr);
  57. cin >> max_time;
  58.  
  59. ll l = 0, r = 1e18, ans = -1;
  60.  
  61. while (l <= r) {
  62. ll mid = (l + r) >> 1;
  63.  
  64. if (check(mid)) {
  65. ans = mid;
  66. l = mid + 1;
  67. }
  68. else {
  69. r = mid - 1;
  70. }
  71. }
  72.  
  73. cout << ans << '\n';
  74. }
Success #stdin #stdout 0.01s 5272KB
stdin
5
stdout
12