danielvitor23

Maximum Product

Apr 28th, 2023
1,204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef int64_t i64;
  5.  
  6. int sz;
  7. i64 a, b;
  8. i64 ans, maxAns;
  9. string lo, hi;
  10.  
  11. pair<i64, string> dp[19][2][2][2];
  12. bool calc[19][2][2][2];
  13.  
  14. pair<i64, string> solve(int idx, bool st, bool canLo, bool canHi, i64 val) {
  15.   if (idx == sz) return {1LL, ""};
  16.  
  17.   if (calc[idx][st][canLo][canHi])
  18.     return dp[idx][st][canLo][canHi];
  19.  
  20.   pair<i64, string> ans = {-1, ""};
  21.   int l = canLo ? 0 : lo[idx] - '0';
  22.   int r = canHi ? 9 : hi[idx] - '0';
  23.   for (int i = l; i <= r; ++i) {
  24.     bool hasStarted = st | (i != 0);
  25.     auto res = solve(idx + 1, hasStarted, canLo | (l < i), canHi | (i < r), val * (hasStarted ? i : 1));
  26.     ans = max(ans, {(hasStarted ? i : 1) * res.first, to_string(i) + res.second});
  27.   }
  28.  
  29.   calc[idx][st][canLo][canHi] = true;
  30.   return dp[idx][st][canLo][canHi] = ans;
  31. }
  32.  
  33. int main() {
  34.   cin.tie(0)->sync_with_stdio(0);
  35.  
  36.   cin >> a >> b;
  37.  
  38.   lo = to_string(a);
  39.   hi = to_string(b);
  40.  
  41.   sz = max(lo.size(), hi.size());
  42.  
  43.   while (lo.size() < sz) lo = '0' + lo;
  44.   while (hi.size() < sz) hi = '0' + hi;
  45.  
  46.   string ans = solve(0, 0, 0, 0, 1).second;
  47.  
  48.   int cnt = 0;
  49.   while (ans[cnt] == '0') ++cnt;
  50.  
  51.   cout << ans.substr(cnt) << '\n';
  52. }
Advertisement
Add Comment
Please, Sign In to add comment