Table of Contents

ExplanationImplementation

Explanation

Let's define the function pref(x)\mathtt{pref}(x) to return the sum of digits among all integers from 00 to xx inclusive. Then, the answer for each query will be pref(r)pref(l1)\mathtt{pref}(r) - \mathtt{pref}(l-1).

We can calculate pref(x)\mathtt{pref}(x) using digit dp. Let nn be the number of digits in xx. The maximum sum of digits among all numbers with at most nn digits is 9n9n. Under the problem constraints, nn can be at most 1616.

We can define the following dp state: dp[i][j][b]\mathtt{dp[i][j][b]} = number of integers having exactly ii digits with sum of digits jj and a freedom value of bb (which is either 00 or 11).

  • If b=0b = 0, then the first ii digits of the state is equivalent to the first ii digits of xx. In this case, when placing the i+1i+1'th digit, it cannot exceed the i+1i+1'th digit of xx.

  • If b=1b = 1, then there exists some dd where d<id < i and the dd-th digit that we placed is less than the dd-th digit of xx. In this case, we already know our integer must be less than xx, regardless of what digit we place next.

For transitions, we must consider the three cases where bb remains 00, bb remains 11, and bb goes from 00 to 11.

Finally, the sum of digits among all integers with exactly ii digits and does not exceed xx is given by j=09nb=01dp[n][j][b]j\sum_{j=0}^{9n} \sum_{b=0}^1 \mathtt{dp[n][j][b]} \cdot j. However, we still have to add the sum of digits for all numbers with less than nn digits, which can be precalculated.

Implementation

Time Complexity: O(n2)\mathcal{O}(n^2) for each query.

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAX_LEN = 17;
ll ans_pow10[MAX_LEN];
ll pref(ll upper) {
string upper_str = to_string(upper);
int n = upper_str.length();

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!