hijibijee

Maximum sum of digits count in range L to R

Aug 11th, 2021 (edited)
1,124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define ll long long
  3. #define endl '\n'
  4. #define IOS ios::sync_with_stdio(0); cin.tie(0);
  5. #define FIO freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
  6. #define MOD 1000000007LL
  7. //#define MOD 998244353LL
  8. #define all(x) (x).begin(),(x).end()
  9.  
  10. using namespace std;
  11.  
  12. vector<vector<vector<ll>>> dp;
  13.  
  14. ll f(int rem, int i, string mx, bool isLess){ // This function counts total number of x, having sumOfDigits(x) == s in range 1 to mx
  15.     if(rem < 0) return 0;
  16.     if(rem == 0) return 1;
  17.     if(i == mx.length()) return 0;
  18.  
  19.     if(dp[rem][i][isLess] != -1) return dp[rem][i][isLess];
  20.  
  21.     int d = mx[i] - '0';
  22.     ll ret = 0;
  23.     if(!isLess){ // We can choose digits from 0 to mx[i]
  24.         for(int currD = 0; currD < d; currD++) ret += f(rem - currD, i + 1, mx, true);
  25.         ret += f(rem - d, i + 1, mx, false);
  26.     }
  27.     else{ // We can choose any digit from 0 to 10
  28.         for(int currD = 0; currD < 10; currD++) ret += f(rem - currD, i + 1, mx, true);
  29.     }
  30.  
  31.     dp[rem][i][isLess] = ret;
  32.  
  33.     return ret;
  34. }
  35.  
  36. void init(int s){
  37.     dp.clear();
  38.     dp.resize(s + 1, vector<vector<ll>> (20, vector<ll> (2, -1)));
  39. }
  40.  
  41. int main(){
  42.     #ifndef ONLINE_JUDGE
  43.         FIO
  44.     #endif
  45.     IOS    
  46.  
  47.     ll low, hi;
  48.     cin >> low >> hi;
  49.  
  50.     ll sum = 0, maxCount = 0;
  51.  
  52.     for(int s = 1; s <= 162; s++){ // maximum sum can be 18 * 9 = 162.
  53.         init(s);
  54.         ll uptoHi = f(s, 0, to_string(hi), false);
  55.        
  56.         init(s);
  57.         ll uptoLow = f(s, 0, to_string(low - 1), false);
  58.  
  59.         if(maxCount <= uptoHi - uptoLow){
  60.             maxCount = uptoHi - uptoLow;
  61.             sum = s;
  62.         }
  63.     }
  64.  
  65.     cout << "For sum = " << sum << " number of winner: " << maxCount << endl;
  66.    
  67.     return 0;
  68. }
Add Comment
Please, Sign In to add comment