DuongNhi99

A - Sum of Digits (15-12)

Dec 14th, 2020
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int64_t long long
  3. using namespace std;
  4.  
  5. int a, b;
  6. int64_t dp[20][180][2];
  7. vector<int> digit;
  8.  
  9. void getDigits(int x) {
  10.     digit.clear();
  11.     while(x) {
  12.         digit.push_back(x % 10);
  13.         x /= 10;
  14.     }
  15. }
  16.  
  17. int64_t digitSum(int id, int sum, bool tight) {
  18.     if(id == -1) return sum;
  19.  
  20.     if(dp[id][sum][tight] != -1 && !tight)
  21.         return dp[id][sum][tight];
  22.  
  23.     int64_t res = 0;
  24.     int k = (tight) ? digit[id] : 9;
  25.  
  26.     for(int i = 0; i <= k; ++i) {
  27.         int newTight = tight & (digit[id] == i);
  28.         res += digitSum(id - 1, sum + i, newTight);
  29.     }
  30.  
  31.     if(!tight)
  32.         dp[id][sum][tight] = res;
  33.  
  34.     return res;
  35. }
  36.  
  37. int main() {
  38. #ifdef DN
  39.     freopen("in.txt", "r", stdin);
  40. #endif
  41.     //freopen("CPCRC1C.inp", "r", stdin);
  42.     //freopen("CPCRC1C.out", "w", stdout);
  43.     ios_base::sync_with_stdio(false);
  44.     cin.tie(NULL); cout.tie(NULL);
  45.  
  46.     while(cin >> a >> b) {
  47.         if(a == -1 && b == -1) break;
  48.  
  49.         fill(**dp, **dp + 20 * 180 * 2, -1);
  50.         getDigits(a - 1);
  51.         int64_t ans1 = digitSum(digit.size()-1, 0, true);
  52.  
  53.         fill(**dp, **dp + 20 * 180 * 2, -1);
  54.         getDigits(b);
  55.         int64_t ans2 = digitSum(digit.size()-1, 0, true);
  56.  
  57.         cout << ans2 - ans1 << '\n';
  58.     }
  59.  
  60.     return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment