Advertisement
tepyotin2

5.2 Magic Numbers

Jul 3rd, 2025
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cstring>
  4.  
  5. using namespace std;
  6.  
  7. int m, d;
  8. string num_str;
  9. long long dp[2000][2000][2];
  10. const int MOD = 1e9 + 7;
  11.  
  12. long long go(int pos, int rem, bool tight) {
  13.     if (pos == num_str.length()) {
  14.         return (rem == 0) ? 1 : 0;
  15.     }
  16.  
  17.     if (dp[pos][rem][tight] != -1) {
  18.         return dp[pos][rem][tight];
  19.     }
  20.  
  21.     long long ans = 0;
  22.     int upper_bound = tight ? (num_str[pos] - '0') : 9;
  23.  
  24.     for (int digit = 0; digit <= upper_bound; ++digit) {
  25.         if ((pos + 1) % 2 == 0) { // Even position
  26.             if (digit != d) {
  27.                 continue;
  28.             }
  29.         } else { // Odd position
  30.             if (digit == d) {
  31.                 continue;
  32.             }
  33.         }
  34.  
  35.         bool new_tight = tight && (digit == upper_bound);
  36.  
  37.         int new_rem = (rem * 10 + digit) % m;
  38.  
  39.         ans += go(pos + 1, new_rem, new_tight);
  40.         ans %=  MOD;
  41.     }
  42.  
  43.     return dp[pos][rem][tight] = ans;
  44. }
  45.  
  46. bool is_valid(const string& s) {
  47.     int rem = 0;
  48.     for (int i = 0; i < s.length(); ++i) {
  49.         int digit = s[i] - '0';
  50.         if ((i + 1) % 2 == 0) {
  51.             if (digit != d) return false;
  52.         } else {
  53.             if (digit == d) return false;
  54.         }
  55.         rem = (rem * 10 + digit) % m;
  56.     }
  57.     return rem == 0;
  58. }
  59.  
  60. int main() {
  61.     ios_base::sync_with_stdio(false);
  62.     cin.tie(NULL);
  63.  
  64.     string a, b;
  65.     cin >> m >> d >> a >> b;
  66.  
  67.     num_str = b;
  68.     memset(dp, -1, sizeof(dp));
  69.     long long ans_b = go(0, 0, true);
  70.  
  71.     num_str = a;
  72.     memset(dp, -1, sizeof(dp));
  73.     long long ans_a = go(0, 0, true);
  74.  
  75.     long long ans = (ans_b - ans_a + MOD) % MOD;
  76.     if (is_valid(a)) {
  77.         ans = (ans + 1) % MOD;
  78.     }
  79.  
  80.     cout << ans << endl;
  81.  
  82.     return 0;
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement