DMOJ · year2018p4

The Polar Express

This C++ solution uses digit dynamic programming for DMOJ year2018p4 The Polar Express. Read the reasoning, inspect the code, or try your own test case below.

year2018p4Dynamic programmingDigit dynamic programmingC++24 lines
Solution219of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Digit dynamic programming

The Polar Express matches the numeric range and the digit-DP count of distinct digit sums.

Dynamic programming

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

the_polar_express.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    ll L, R; int sum, ans; ll dp[20][2][163];
    ll fun(string s, int idx, bool lmt, int ds) {
        if (idx == s.size()) return ds == sum;
        if (dp[idx][lmt][ds] != -1) return dp[idx][lmt][ds];
        int up = lmt ? s[idx] - '0' : 9; ll cnt = 0;
        for (int i = 0; i <= up; i++) 
            cnt += fun(s, idx + 1, lmt & (i + '0' == s[idx]), ds + i);
        return dp[idx][lmt][ds] = cnt;
    }
    ll solve(ll val) {
        string s = to_string(val); memset(dp, -1, sizeof(dp));
        return fun(s, 0, 1, 0);
    }
    int main() {
        ios::sync_with_stdio(0); cin.tie(0);
        cin >> L >> R;
        for (sum = 1; sum <= 9 * 18; sum++) {
            if (solve(R) - solve(L-1) > 0) ans++;
        }
        cout << ans << "\n";
    }
        

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 ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.