Problem solution · C++

ABC402 E — Payment Required

ABC402 E — Payment Required: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to michimani AtCoder Solutions.

Technique
Dynamic programming
Source
michimani AtCoder Solutions
Length
54 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For ABC402 E — Payment Required, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 54 lines of C++ from the credited upstream file abc402_e.cpp.
  • The implementation visibly relies on sequence storage, cached states.
  • 2 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from michimani AtCoder Solutions by michimani and is used under the MIT licence.

Full codeABC402 E — Payment Required · C++C++
Use this to learn the idea, then write your own version.
#include <algorithm>#include <functional>#include <iomanip>#include <iostream>#include <vector> using namespace std; struct State {    int solved;    int money;}; int main() {    int n, x;    cin >> n >> x;     vector<int> s(n), c(n), p(n);    for (int i = 0; i < n; i++) {        cin >> s[i] >> c[i] >> p[i];    }     vector<vector<double>> dp(1 << n, vector<double>(x + 1, -1));     function<double(int, int)> solve = [&](int solved, int money) {        if (dp[solved][money] >= 0) return dp[solved][money];         double ret = 0;         for (int i = 0; i < n; i++) {            if (solved & (1 << i)) continue;             if (money < c[i]) continue;             double pp = p[i] / 100.0;             double ev_success = solve(solved | (1 << i), money - c[i]) + s[i];            double ev_failure = solve(solved, money - c[i]);             double ev = pp * ev_success + (1 - pp) * ev_failure;             ret = max(ret, ev);        }         return dp[solved][money] = ret;    };     double ans = solve(0, x);     cout << fixed << setprecision(15) << ans << endl;     return 0;} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗