Explanation
Let's define the function to return the sum of digits among all integers from to inclusive. Then, the answer for each query will be .
We can calculate using digit dp. Let be the number of digits in . The maximum sum of digits among all numbers with at most digits is . Under the problem constraints, can be at most .
We can define the following dp state: = number of integers having exactly digits with sum of digits and a freedom value of (which is either or ).
If , then the first digits of the state is equivalent to the first digits of . In this case, when placing the 'th digit, it cannot exceed the 'th digit of .
If , then there exists some where and the -th digit that we placed is less than the -th digit of . In this case, we already know our integer must be less than , regardless of what digit we place next.
For transitions, we must consider the three cases where remains , remains , and goes from to .
Finally, the sum of digits among all integers with exactly digits and does not exceed is given by . However, we still have to add the sum of digits for all numbers with less than digits, which can be precalculated.
Implementation
Time Complexity: 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!