Advertisement
tepyotin2

5.3 Classy Numbers

Jul 3rd, 2025
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cstring>
  4.  
  5. using namespace std;
  6.  
  7. long long dp[20][4][2];
  8. string S;
  9.  
  10. long long go(int pos, int count, bool tight) {
  11.     if (pos == S.length()) {
  12.         return 1;
  13.     }
  14.  
  15.     if (dp[pos][count][tight] != -1) {
  16.         return dp[pos][count][tight];
  17.     }
  18.  
  19.     long long ans = 0;
  20.     int upper_bound = tight ? (S[pos] - '0') : 9;
  21.  
  22.     for (int digit = 0; digit <= upper_bound; ++digit) {
  23.             int new_count = count + (digit > 0);
  24.  
  25.             if (new_count <= 3) {
  26.                 ans += go(pos + 1, new_count, tight && (digit == upper_bound));
  27.             }
  28.     }
  29.  
  30.     return dp[pos][count][tight] = ans;
  31. }
  32.  
  33. long long solve(long long n) {
  34.     if (n == 0) return 0;
  35.     S = to_string(n);
  36.     memset(dp, -1, sizeof(dp));
  37.  
  38.     return go(0, 0, true);
  39. }
  40.  
  41. int main() {
  42.     ios_base::sync_with_stdio(false);
  43.     cin.tie(NULL);
  44.  
  45.     int T;
  46.     cin >> T;
  47.     while (T--) {
  48.         long long L, R;
  49.         cin >> L >> R;
  50.         cout << solve(R) - solve(L - 1) << "\n";
  51.     }
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement