Advertisement
milon34

how many integers [A-B] digit sum equal to x (digit dp)

Jan 22nd, 2023
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. #define ll long long int
  5. int dp[12][2][95];
  6. string s;
  7. int x;
  8.  
  9. int solve(int pos, int isSmall, int digitSum) {
  10.     if (pos == s.size()) {
  11.         return (digitSum == x);
  12.     }
  13.     if (dp[pos][isSmall][digitSum] != -1) {
  14.         return dp[pos][isSmall][digitSum];
  15.     }
  16.     int low = 0, high = s[pos] - '0';
  17.     if (isSmall) {
  18.         high = 9;
  19.     }
  20.     int res = 0;
  21.     for (int i = low; i <= high; i++) {
  22.         int new_sm = isSmall | (i < high);
  23.         int val = solve(pos + 1, new_sm, digitSum + i);
  24.         res += val;
  25.     }
  26.     return dp[pos][isSmall][digitSum] = res;
  27. }
  28.  
  29. int main() {
  30.     memset(dp, -1, sizeof(dp));
  31.     cin >> s >> x;
  32.     cout << solve(0, 0, 0);
  33.     return 0;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement