We need to compute sum of numbers in [l, r] (both inclusive) such that each number has at most k distinct digits. l and r up to 1e18, so digit DP. k ≤ 10.
We need to compute sum modulo MOD = 998244353. Classic digit DP: count and sum of numbers satisfying some property. Here property: number of distinct digits ≤ k.
We need to sum the numbers themselves, not just count. So DP state includes: position (from most significant to least), tight flag, maybe leading zero flag, and a mask of digits used so far. But digits are 0-9. However we also have leading zeros: leading zeros should not be counted as distinct digits. So we need to treat leading zeros specially: when we are still in leading zeros, digit 0 is not considered as a used digit. Once we put first non-zero digit, zeros after that are considered as digit 0 and count if not already used.
But careful: The number 0 itself? Since l≥1, so no need for zero. But we might have to handle numbers with leading zeros when length is less than max length. Typically we do digit DP from most significant to least, with a flag "started" indicating we have placed a non-leading digit. Also a mask of used digits (bits for 0-9). But mask for digits after started; before started, we haven't placed any digit so mask is empty, and digit 0 is not counted. However, after started, digit 0 is counted as part of mask if used.
But we also need to track the number of distinct digits (popcount(mask)). So we can use mask (10 bits) which is manageable (2^10 = 1024). Since k ≤ 10, we can even prune if popcount > k, but we can just compute DP with mask and at the end consider only masks with popcount ≤ k.
We need sum of numbers. Classic approach: DP returns pair (count, sum) for given state. The sum is the total sum of numbers formed from this state to the end (including digits already placed). When we append a digit d at current position, the contribution to the sum for the new number is: we have some prefix value prev_val, and the remaining digits are formed. However, in DP we can compute recursively: if we have state (pos, tight, started, mask) and we are at position i (0-index from most significant), we want to build numbers from this position to end. But we need to know the current prefix value (the number formed so far) to add contributions. But we can avoid storing prefix value by computing sums as we go: when we place digit d, the new number's value is prev_val * 10 + d, summed over all completions. So if we know, for a given state, the sum of the suffixes (the values contributed by the lower positions) and the count, we can combine with the current digit's place value.
Typically DP: we process digits left to right. At each step, we choose digit d (subject to tight constraint). Then we recursively compute for next position with new tight flag, new started flag, new mask. Let the recursive result be (cnt_next, sum_next). The numbers formed from this choice will have the prefix so far? But we need to incorporate the current digit's contribution. The prefix so far (the number built up to the previous positions) is not part of the state, but we can pass it as parameter? That would explode. Instead, we can compute the contribution from the current digit in terms of its place value. When we are at position i (from left, with total length L), the digit at this position contributes d * 10^{remaining positions} to the final number, plus the contribution of the suffix. So if we define state at position i, we want to know the sum of numbers formed from this position onward, but without considering the higher digits already placed. However, we need to combine higher digits' contributions eventually. So we need DP that returns, for a given state, (count, sum) where sum is the total sum of the numbers formed from this state, considering that the digits already placed (the prefix) are not included, only the suffix part's value. Then when we combine, if we choose digit d at this position, and we have remaining positions = rem (including current? careful). Usually, we treat DP as starting at index pos (0-based from most significant) and we have to fill positions from pos to the end. The numbers we construct from this state correspond to the suffix of length rem. The full number will be: prefix * 10^{rem} + suffix, where prefix is the already fixed part (the digits chosen before pos). But we don't store prefix. However, when we compute total sum for the top-level DP, we don't need the prefix; we just need the sum of full numbers. So we can compute DP for the entire number from the start, but we need to incorporate the value contributed by each digit as we place it.
A standard technique: In the DP recursion, we return a pair (count, sum) for numbers that can be formed from the current position to end, where the "sum" is the sum of the suffix values (i.e., the numeric value of the digits we will place from this position onward, as if they formed a number of length rem). But then when we combine, suppose we are at position pos (with rem positions left). We choose digit d. The suffix from the next position (pos+1) will have length rem-1. Let (cnt_next, sum_next) be result from that state. Then the numbers formed by choosing d at pos will have: the value contributed by d is d * 10^{rem-1} plus the suffix value sum_next (which is the value of the rem-1 digits). So total sum for this branch = (cnt_next * (d * 10^{rem-1}) + sum_next) modulo MOD. And total count = cnt_next. But careful: if started is false and we choose d=0 (i.e., we are still in leading zeros), then the number is not yet started. In that case, the effective digit does not contribute to the number because it's a leading zero. However, we need to treat it specially: When we are not started and we choose 0, we are still not started; the number's length might be less than total L. Actually, we need to handle numbers with variable length. Typical approach: We pad the number with leading zeros to make it exactly L digits (where L is the number of digits in the upper bound). But we need to count numbers from 0 to bound inclusive? Since l and r are up to 1e18, we can compute f(N) = sum of numbers from 0 to N satisfying condition (including 0 maybe, but we will handle l-1). Then answer = (f(r) - f(l-1) + MOD) % MOD. However, we must exclude 0 if it's included? But l≥1, so f(l-1) doesn't include 0? Actually f(0) would include 0. But 0 has digit 0 (only one digit) so it would be counted if k >= 1. However, when we compute f(N) for N>=0, we must count numbers from 0 to N inclusive. But later we subtract f(l-1), so any numbers < l are subtracted. Since l≥1, we won't include 0 in final answer. So it's fine to include 0 in f(N). But we need to handle leading zeros correctly: For numbers less than 10^{L-1} (where L is number of digits in N), they have fewer digits. In the DP, we treat the number as having exactly L digits with leading zeros. Then we need to ensure that leading zeros do not count as distinct digits. Also for the number 0, all digits are zeros and we consider that it has started? Actually, number 0 is represented as L zeros, but we need to interpret that as the number 0. Usually, we treat the "started" flag: if started is false, we have not yet placed any non-zero digit. When we finish, if started is still false, that means the number is 0. So we include 0 as a valid number if it satisfies condition: distinct digits in the actual number (which is 0) are just digit 0, and count=1. In our DP, if we never start, the mask would be empty because we didn't count zeros. But we need to treat the number 0 as having digit 0. So we can handle that by special case: at the end of recursion, when we have processed all positions, if started is false (i.e., we put all zeros), then the number is 0, and we need to consider its mask as containing digit 0 (since the number is 0). So the condition for number 0 is: distinct digits = 1 (only 0) if k>=1. So we can incorporate that at base case: pos == L (i.e., processed all digits). Then we need to decide if this constructed number (with leading zeros) is valid. Typically, we compute DP that returns count and sum of numbers that satisfy condition. So in recursion, we only accumulate when we reach the end. At the end, we need to evaluate whether the built number (with its actual digits) satisfies the distinct digit condition. But we have mask that may not include zeros if we never started. So we need to treat mask: if started is false, then the actual number is 0, so its digits are {0}. So the condition is: if not started, then distinct digits = 1 (0). So we can treat that case separately.
Alternatively, we could modify DP: treat leading zeros as not counting, but at the end, if we never started, then we explicitly consider number 0. That might be simpler.
Thus DP design:
We define a function solve(limit) that returns sum of numbers from 0 to limit (inclusive) that have at most k distinct digits.
We convert limit to string s of digits, length L.
We define DP[pos][tight][started][mask] where:
- pos: index from 0 to L (0 = most significant digit). When pos == L, we are done.
- tight: 0/1 indicates whether prefix equals limit's prefix so far. If 1, then we can only choose digits up to s[pos]; else 0-9.
- started: 0/1 indicates whether we have placed a non-zero digit yet. If 0, we are still in leading zeros.
- mask: bitset of 10 bits representing distinct digits used so far. However, we only need to store mask when started=1. When started=0, mask is always 0 (no digits used). But we can still store mask but it will be 0. To reduce states, we can have mask only when started=1. But for simplicity, we can keep mask always, but it will be 0 when started=0. Since mask dimension is 1024, it's manageable, but we need to avoid MLE if we cache all states. L <= 19 (since 1e18 < 10^18, max 19 digits? Actually 10^18 is 1 followed by 18 zeros, so maximum digits = 19? 1e18 = 1000000000000000000 (19 digits). So L <= 19. State count: pos 20, tight 2, started 2, mask 1024 => 2022*1024 = 81920, which is fine. But we also need to store sum and count per state, but we can memoize (pos, tight, started, mask) -> (count, sum). That's acceptable.
But careful: DP will be called multiple times? For each limit, we compute DP once. So memory not an issue.
We need to compute sum modulo MOD. Also we need to handle large numbers, so use 64-bit then mod.
DP recursion:
Define function dfs(pos, tight, started, mask):
-
if pos == L:
If started == 0: number is 0. Check condition: distinct digits = 1 (digit 0). So if k >= 1, this number (0) is valid. Return count=1, sum=0 (since number 0 sum is 0). Else return (0,0).
else: number is positive (or could be 0? No, started=1 means at least one non-zero digit). Check popcount(mask) <= k. If yes, return (1,0) for count and sum? Actually at leaf, the suffix is empty (no more digits), so the sum contributed by this suffix is 0, and we have accounted for all digits earlier. In our DP, the sum we return is the value of the suffix (the digits from pos to end) which in this case is empty (value 0). So we should return (1,0) for each valid completion, meaning there is one number with suffix value 0. The total sum of numbers will be built by adding contributions from earlier digits.
-
Otherwise, compute the maximum digit we can choose: up = s[pos] - '0' if tight else 9.
-
Initialize cnt_total = 0, sum_total = 0.
-
For d from 0 to up:
new_tight = tight and (d == up? Actually d == up? We need to check if tight and d == s[pos] - '0' then remain tight, else 0.
new_started = started or (d != 0)
new_mask = mask
if new_started:
if started == 0 and d == 0: But this case, new_started remains false. Actually new_started is true if d != 0, because started might already be true. So if new_started true, we need to update mask: set bit for digit d. But careful: if d==0 and started false, new_started false, we don't add 0. If d==0 and started true, then we are adding a zero after started, so we need to include 0 in mask. So condition: if new_started then we include digit d. But if started was already true and d=0, we need to include 0. So yes, if new_started is true, then we set bit for d. So: if new_started: new_mask = mask | (1 << d). But what about case started false and d!=0: new_mask becomes (0) | (1<<d). That's correct. If started true and d=0: new_mask = mask | (1<<0) adds zero. Good.
else: new_mask = 0? Actually if new_started false, we are still leading zeros, so mask remains 0 (since we haven't used any digit). However, we can just set new_mask = mask? But mask should be 0 because we never set bits when started false. Since we always pass mask=0 when started false, it's fine. But if we update from started false to false, we keep mask 0.
Then we call dfs(pos+1, new_tight, new_started, new_mask) -> (cnt_next, sum_next).
Now we need to compute contribution for numbers formed from this branch. The current digit is d, and the remaining positions count (from pos+1 to end) = rem = L - pos - 1. The digit d contributes to the final number as d * 10^{rem}. But careful: If we are still not started (i.e., new_started false), then this digit is a leading zero, and it should not contribute to the number's value. Actually, if we are still in leading zeros, the digit d=0, and it's not part of the number; the number's value is determined by later non-zero digits. So in that case, the contribution d * 10^{rem} should be 0. However, our recursion returns sum_next which is the suffix value (the number formed by the remaining digits, possibly with leading zeros). But if we haven't started yet, the suffix may also be leading zeros. The full number's value is just the suffix's value (since the leading zeros don't add value). So for the branch where we are still not started, the total sum for this branch should be simply sum_next (since adding leading zero doesn't change value). But also count remains cnt_next. However, if we are not started, we also should ensure that we don't double count zeros? Actually, when we are at a position and we choose d=0 and started=false, we are effectively still not started, and the number's value from the prefix (all zeros) is 0. So the total value from this branch is just the value contributed by the suffix. This is consistent with treating that the digit d (0) does not add any value. So we can compute:
if new_started:
contribution = (cnt_next * (d * pow10[rem]) + sum_next) % MOD
else:
contribution = sum_next (since d=0 and not started, so no addition). But note: when new_started is false, d must be 0, because if d !=0, new_started becomes true. So indeed d=0. So we can safely set contribution = sum_next.
Now we need pow10[rem] modulo MOD precomputed for rem up to 18. Since numbers up to 10^18, rem up to 18 (since L up to 19, rem = L - pos - 1, max 18). So we can precompute pow10_mod[0..18] = 10^rem % MOD.
But careful: The DP recursion will combine many branches. We'll memoize results per state (pos, tight, started, mask). Since mask dimension is 1024, but many masks will be unreachable because of the distinct digit constraint? Actually we may generate many masks. However, it's fine.
But we also need to filter by popcount(mask) <= k at the leaf. However, we could prune earlier: if popcount(mask) > k, we can return (0,0) immediately regardless of tight? Actually, if at any state the current mask has popcount > k, then no matter what digits we add later, the distinct digits will remain >= popcount(mask) (can only increase or stay same). So we can return 0 early. That will reduce states. So we can check: if started and popcount(mask) > k: return (0,0). Even if not started, mask=0, popcount=0 <=k.
Now, note: For states where started=0, mask=0, it's fine.
Also, at leaf, if started=0, we handle number 0 separately as described: condition k>=1. So return (1,0) if k>=1 else (0,0). However, note that we may have the possibility that k=0? k>=1 according to constraints (1 ≤ k ≤ 10). So k is at least 1. So number 0 always qualifies? Actually if k=1, 0 qualifies. So we can always count 0 when started=0 leaf. But if k=0, not allowed. So for k≥1, 0 is counted.
Thus in solve(limit) we compute DP(0, tight=1, started=0, mask=0). The result sum will include 0. That's fine.
Now we need to compute f(r) and f(l-1) and subtract mod.
Edge Cases: l can be 1, so l-1 = 0, f(0) should include 0 only if it qualifies. Since k≥1, 0 qualifies, sum 0. So f(0)=0. So answer = f(r). That's fine.
Now we need to be careful about overflow and modulo. Use long long, mod operations.
Now complexity: DP states about 20 * 2 * 2 * 1024 = ~82k, each state iterates over up to 10 digits. So ~820k operations, trivial.
But we must memoize per DP call. Since we have to compute two DP calls (for r and l-1), we can reuse DP for each limit separately (since tight and limit digits differ). But we can also implement a DP that works for a given string s.
Implement solve(limit): convert limit to string digits, L = length. Precompute pow10_mod[0..L] maybe.
Define memo[pos][tight][started][mask] as -1 for count (or pair). Since tight is 0/1, started 0/1, mask 0..1023.
But we can't store 4D array with that size? Actually we can: dimensions: pos 20, tight 2, started 2, mask 1024 => 2022*1024=81920. That's small. Use vector of pairs or two arrays: long long dp_count[20][2][2][1024], dp_sum[20][2][2][1024] with -1 sentinel.
But note: For each DP call, the limit string is fixed. So we can just have a memo as a map? Simpler: use arrays with -1.
Alternatively, we can implement recursion with memoization using unordered_map keyed by state. But array is faster.
Implementation details:
- Precompute pow10_mod[0..20] mod MOD.
- For each limit, we compute s = to_string(limit).
- L = s.length().
- Initialize memo arrays with -1 for count; we can have two separate 4D arrays: cnt_memo[20][2][2][1024], sum_memo[20][2][2][1024] using long long (or int64). Use -1 for cnt to indicate not computed.
But note: mask only matters when started=1? But we can store for all. That's fine.
- Write recursive function:
pair<ll, ll> dfs(int pos, bool tight, bool started, int mask) {
if (pos == L) {
if (!started) {
// number 0
return (k >= 1) ? make_pair(1LL, 0LL) : make_pair(0LL, 0LL);
} else {
if (__builtin_popcount(mask) <= k) return {1, 0};
else return {0, 0};
}
}
// early pruning: if started and popcount(mask) > k, return 0
if (started && __builtin_popcount(mask) > k) return {0, 0};
int ti = tight ? 1 : 0;
int st = started ? 1 : 0;
if (cnt_memo[pos][ti][st][mask] != -1) return {cnt_memo[pos][ti][st][mask], sum_memo[pos][ti][st][mask]};
int up = tight ? (s[pos] - '0') : 9;
ll total_cnt = 0;
ll total_sum = 0;
for (int d = 0; d <= up; ++d) {
bool new_tight = tight && (d == up);
bool new_started = started || (d != 0);
int new_mask = mask;
if (new_started) {
new_mask = mask | (1 << d);
}
// But if started is false and d==0, new_started false, new_mask stays 0.
auto [cnt_next, sum_next] = dfs(pos+1, new_tight, new_started, new_mask);
if (cnt_next == 0) continue;
int rem = L - pos - 1;
if (new_started) {
ll add = (cnt_next % MOD) * ((d * pow10_mod[rem]) % MOD) % MOD;
total_sum = (total_sum + add + sum_next) % MOD;
} else {
total_sum = (total_sum + sum_next) % MOD;
}
total_cnt = (total_cnt + cnt_next) % MOD; // but cnt can be large, we can mod it as well (since only used in multiplication mod). However, careful: cnt is used in next recursion's multiplication mod, so we can store cnt modulo MOD as well. But later we may need count for other DP states; as long as we treat mod consistently, it's fine because we only multiply cnt with numbers mod MOD to compute sum. However, the count itself may be used for other branches and as a return value, but all operations are modulo MOD for sum, but for count we can also keep modulo MOD because the count is used only in multiplication with mod. There's no need for exact count beyond MOD since we only need final sum mod MOD. So we can store cnt modulo MOD. That's acceptable.
But careful: In the recursion, the count is used to compute contributions, but we mod it, that's fine. However, there is no need to mod count for correctness because we only care about sum mod MOD. But it's safe to mod count as well.
So we can keep total_cnt mod MOD.
}
cnt_memo[pos][ti][st][mask] = total_cnt % MOD;
sum_memo[pos][ti][st][mask] = total_sum % MOD;
return {cnt_memo[pos][ti][st][mask], sum_memo[pos][ti][st][mask]};
}
But note: We use pow10_mod[rem] mod MOD. However, note that the actual contribution of digit d to the number is d * 10^{rem} (in integer arithmetic) and we are summing over many numbers. Since we take modulo MOD, we can compute (d * pow10_mod[rem]) % MOD and multiply by cnt_next mod MOD.
Now, about pow10_mod[rem]: 10^{rem} may exceed 64-bit, but we compute mod. Since rem <= 18, 10^{18} fits in 64-bit actually, but modulo we can precompute mod.
But note: The sum we compute is modulo MOD, but the count may be large (up to r ~10^18). However, storing count modulo MOD is okay because we only use it in multiplication modulo MOD. However, is there any issue when we compute sum? The sum formula: total_sum += cnt_next * (d * 10^{rem}) + sum_next. Since we are working mod MOD, we can mod everything. So it's fine.
But we need to be careful: The recursion also uses the count for early pruning? Not directly. So it's fine.
Now, we need to ensure that for states where started=0 and mask=0, the memoization works. Mask is 0, so that's fine.
Now, we need to pass k as a global variable (or capture).
Now, we need to compute f(r) and f(l-1). For l-1, if l=1, then l-1=0. We'll handle.
Now test with examples.
Example 1: l=10, r=50, k=2.
We need sum from 10 to 50 with at most 2 distinct digits. According to example, answer = 1230 (which is sum of all numbers because k=2 and all numbers from 10 to 50 have at most 2 distinct digits? Actually 10: digits {1,0} distinct count 2, ok; 11: {1} count 1; 12: {1,2} count2; ... up to 50. Let's check: number 33: {3} count1; 49: {4,9} count2; 50: {5,0} count2. So all numbers from 10 to 50 have at most 2 distinct digits? Could there be a number with 3 distinct digits? e.g., 123 is >50. So all numbers from 10 to 50 indeed have at most 2 distinct digits? Actually 10..50 are two-digit numbers. The maximum distinct digits in two-digit numbers is 2 (if digits are different). So yes, all numbers from 10 to 50 satisfy. So answer = sum 10..50 = (5051/2 - 910/2) = (2550/2? Wait compute: sum 1..n = n(n+1)/2. Sum 1..50 = 1275, sum 1..9 = 45, difference = 1230. So correct.
Our DP for limit=50 (k=2) should compute sum of numbers 0..50 with condition. Then subtract f(9) (since l-1=9). f(9) should be sum 0..9 with condition. For k=2, all numbers 0..9 have at most 2 distinct digits (they have 1 digit). So f(9) = sum 0..9 = 45 (including 0). Then f(50) = sum 0..50 = 1275? Actually sum 0..50 = sum 1..50 = 1275. But careful: 0 is included, sum = 1275. Then f(50)-f(9) = 1275-45 = 1230. Good.
Let's test: f(50) DP should return sum of numbers 0..50 satisfying condition. We'll trust.
Second example: l=1, r=2345, k=10. Since k=10, any number qualifies. So sum 1..2345 = 23452346/2 = 2750685? Let's compute: 23452346 = 23452346. 23452000=4,690,000; 300=703,500; 40=93,800; 6=14,070; sum ~5,501,370? Actually 23452346 =? Let's compute: 23452346 = 2345(2300+46) = 23452300=5,393,500; 234546=107,870; total=5,501,370. Half = 2,750,685. Yes matches 2750685. So DP should give that.
Third example: l=101, r=154, k=2, answer=2189. We can test later.
Now check DP correctness for number 0: In solve(limit), we include 0. So f(0) returns 0 sum, count maybe 1. Good.
Now one nuance: When started is false and we are at some position and we choose digit 0, we do not count that digit as used. That's fine. However, consider number like 101. It has digits 1,0,1 distinct digits {0,1}=2. In DP, when we process first digit '1', started becomes true, mask = {1}. Then next digit '0', mask becomes {1,0} (since started true). Then next digit '1', mask stays {1,0}. At end popcount=2, qualifies. Good.
Now consider number 100: digits 1,0,0 distinct =2. DP: first digit '1', mask {1}; second '0', mask {1,0}; third '0', mask {1,0}. Good.
Now number 0: started false all the way, leaf: we check condition separately. We said if k>=1, count 1, sum 0. Good.
Now consider numbers with leading zeros like 0012? In DP we pad to length L. For limit=12 (L=2), we represent numbers as two-digit strings: 00,01,...,12. For number 5, it's represented as "05". The DP will process: first digit 0, started false; second digit 5, started becomes true, mask includes 5; then leaf, started true, mask popcount=1. The value contributed: first digit 0 not started => no addition; second digit 5 with rem=0? Actually L=2: positions 0 and 1. At pos=0, d=0, started false, rem=1, we go recursion. At pos=1, we choose d=5, started becomes true, rem=0, we call dfs(pos=2). Then at leaf, return cnt=1, sum=0. Then at pos=1 branch: new_started true, cnt_next=1, sum_next=0, rem=0, so contribution = cnt_next * (5 * 10^0) + sum_next = 5. Then at pos=0 branch: since new_started false, contribution = sum_next = 5. So total sum =5, correct.
Now for number 0: "00". Both digits 0, started false throughout. At leaf, started false, return count=1, sum=0. Branch contributions: pos=0: d=0, new_started false, rem=1, we get sum_next from pos=1. At pos=1: d=0, new_started false, rem=0, get from leaf count=1, sum_next=0, contribution = sum_next =0 (since new_started false). So total sum 0. Good.
Now we need to ensure early pruning: if started and popcount(mask) > k, return (0,0). That will prune many branches. Since k up to 10, eventually many masks may have popcount > k, but it's okay.
Now complexity: For each DP state, we iterate over digits 0..up (max 10). With early pruning, many states will be pruned earlier.
But we have to store memo for all masks even if many are unreachable. 81920 states is fine.
Now one nuance: The DP includes the state mask, which can be up to 1024. But we also have tight and started. The number of states is small. We'll implement with arrays.
But we need to be careful with caching because tight=1 states are specific to the tight condition; they are not many. So we can use memoization with map? Actually, arrays are fine but we need to index by mask, and we have pos up to 19 (0..18 maybe). L max? 1e18 is 10^18, which is 19 digits? Actually 10^18 = 1,000,000,000,000,000,000 (19 digits). So L max = 19. So pos index from 0 to 19. 20 positions.
Define L = s.length().
We'll allocate cnt[20][2][2][1024] and sum[20][2][2][1024] as long long, initialized to -1 for cnt. But 2022*1024 = 81920, each 8 bytes ~ 655KB for cnt, same for sum -> about 1.3MB, fine.
But we need to reset between DP calls (for r and l-1). We can either use vectors and fill with -1 each time, or allocate inside solve function.
We'll implement solve(limit) that does:
string s = to_string(limit);
int L = s.size();
vector<vector<vector<vector>>> cnt(L+1, vector<vector<vector>>(2, vector<vector>(2, vector(1024, -1))));
similar for sum.
But that would be heavy per call: L+1 * 2 * 2 * 1024 = ~82k, times 2 calls = 164k, it's fine. But using vector of vectors with many nested vectors could have overhead. Better to use plain arrays: ll cnt[20][2][2][1024], sum[20][2][2][1024]; and we can clear with memset for the first dimension? Since we only use positions from 0..L, we can initialize all entries to -1 with memset for entire array. That's even simpler: define arrays of size [20][2][2][1024] as static inside solve? But we need to reset each call. We can define them as local arrays and then use nested loops to set to -1, or use memset. Since total elements = 2022*1024 = 81920, we can memset each array: sizeof(cnt) is 81920 * 8 = 655360 bytes, okay.
But we must be careful about indexing: we will use pos as first index, then tight as 0/1, started as 0/1, mask as 0..1023. So we can declare:
ll cnt[20][2][2][1024];
ll sum[20][2][2][1024];
memset(cnt, -1, sizeof cnt); // set all bytes to -1 (which for signed 64-bit is -1, okay).
memset(sum, 0, ?) but we will only use if cnt != -1; we can also set sum to -1 but we use pair. Alternatively we can store both in a struct.
Simplify: Use pair<ll,ll> memo[20][2][2][1024]; with a flag for computed. But we can store count as -1 sentinel. We'll do:
ll cnt_memo[20][2][2][1024];
ll sum_memo[20][2][2][1024];
Set cnt_memo to -1 initially.
Then in dfs, if cnt_memo[pos][tight][started][mask] != -1, return.
At end, assign.
One nuance: tight and started are bool, we need to convert to int for indexing.
Now we need to precompute pow10_mod[0..L]. Since L <= 19, we can compute pow10_mod[i] = 10^i % MOD.
Now we need to be careful about the modulo when computing contributions: We do total_sum = (total_sum + add + sum_next) % MOD, where add = cnt_next * (d * pow10_mod[rem]) % MOD. Since cnt_next may be large but we store modulo MOD? Actually cnt_next we store modulo MOD; but we also need to multiply with d * pow10_mod[rem] mod MOD. So we can store cnt mod MOD. However, note that cnt_next might be used in other contexts? Only for multiplication. So it's safe to store cnt modulo MOD. But careful: In early pruning and in leaf, we return count=1 for valid numbers. That 1 is small, mod is 1. For bigger counts, they may exceed MOD, but storing modulo is fine because we only use it in multiplication modulo MOD. The DP recursion doesn't require the exact count for branching, only the value of sum. So we can store count modulo MOD.
But one nuance: The condition for pruning is based on popcount(mask) which doesn't depend on count. So storing count modulo MOD is fine.
Thus we can store cnt modulo MOD.
Now implement:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 998244353;
int k;
string s;
int L;
ll pow10_mod[20];
ll cnt_memo[20][2][2][1024];
ll sum_memo[20][2][2][1024];
pair<ll, ll> dfs(int pos, bool tight, bool started, int mask) {
if (pos == L) {
if (!started) {
// number 0
if (k >= 1) return {1, 0};
else return {0, 0};
} else {
if (__builtin_popcount(mask) <= k) return {1, 0};
else return {0, 0};
}
}
// early prune
if (started && __builtin_popcount(mask) > k) {
return {0, 0};
}
int ti = tight ? 1 : 0;
int st = started ? 1 : 0;
if (cnt_memo[pos][ti][st][mask] != -1) {
return {cnt_memo[pos][ti][st][mask], sum_memo[pos][ti][st][mask]};
}
int up = tight ? (s[pos] - '0') : 9;
ll total_cnt = 0;
ll total_sum = 0;
for (int d = 0; d <= up; ++d) {
bool new_tight = tight && (d == up);
bool new_started = started || (d != 0);
int new_mask = mask;
if (new_started) {
new_mask |= (1 << d);
}
auto [cnt_next, sum_next] = dfs(pos+1, new_tight, new_started, new_mask);
if (cnt_next == 0) continue;
int rem = L - pos - 1;
if (new_started) {
ll digit_contrib = (d * pow10_mod[rem]) % MOD;
ll add = (cnt_next * digit_contrib) % MOD;
total_sum = (total_sum + add + sum_next) % MOD;
} else {
total_sum = (total_sum + sum_next) % MOD;
}
total_cnt = (total_cnt + cnt_next) % MOD;
}
cnt_memo[pos][ti][st][mask] = total_cnt;
sum_memo[pos][ti][st][mask] = total_sum;
return {total_cnt, total_sum};
}
ll solve(ll limit) {
if (limit < 0) return 0; // for l-1= -1? But l>=1 so not needed.
s = to_string(limit);
L = s.length();
// precompute pow10_mod up to L
pow10_mod[0] = 1;
for (int i = 1; i <= L; ++i) {
pow10_mod[i] = (pow10_mod[i-1] * 10) % MOD;
}
// Initialize memo with -1
memset(cnt_memo, -1, sizeof cnt_memo);
// sum_memo will be overwritten, but we only check cnt_memo for computed.
auto [cnt, sum] = dfs(0, true, false, 0);
return sum % MOD;
}
int main() {
ll l, r;
cin >> l >> r >> k;
ll ans = (solve(r) - solve(l-1) + MOD) % MOD;
cout << ans << endl;
return 0;
}
Now test with given examples.
But wait: There is a subtle bug: The DP sum includes the number 0. For l-1 = 0, solve(0) returns 0 sum (since 0 sum). So subtraction works.
Now test with l=10, r=50, k=2. Compute f(50) and f(9). Let's simulate roughly.
But we must ensure that the DP for limit works correctly when limit has leading digit non-zero. It should.
But we might need to consider that numbers with fewer digits than L are counted via leading zeros. That's correct.
Now test with k=1 example: Input: 10 50 1. According to statement answer is 110 (11+22+33+44). Let's compute with our algorithm. f(50) for k=1: sum of numbers from 0 to 50 with at most 1 distinct digit. That includes numbers: 0,1,2,...,9,11,22,33,44? Also 55? 55 > 50. Also 00? Actually 0..9 are all single-digit numbers, each has 1 distinct digit, so they qualify. Also numbers like 10? Digits 1 and 0 -> 2 distinct, not qualify. 12,13,... not qualify. 11 qualifies (1 distinct). 22 qualifies. 33,44 qualifies. 55 >50. Also 100? but >50. So f(50) includes 0-9,11,22,33,44. Sum = sum 0..9 =45, plus 11+22+33+44 =110, total =155. f(9) includes 0..9 sum=45. So answer =155-45=110. Good.
Our DP for k=1 should compute that.
Now test with third example: 101 154 2. Expected 2189. We can test mentally or later.
But there might be issues with the DP's handling of the number 0 and leading zeros, especially when k=0? Not needed.
Potential pitfalls:
-
We used __builtin_popcount(mask) which works for int up to 32-bit. mask is up to 1023, fine.
-
pow10_mod[rem] we compute mod MOD. But rem = L - pos - 1, maximum 18. 10^18 fits in 64-bit, but mod we compute.
-
The DP recursion returns sum for suffix. When we combine, for new_started true branch, we add cnt_next * (d * 10^rem) + sum_next. This correctly accounts for the digit's contribution. The sum_next already includes contributions of lower digits. Since we process left to right, this is standard.
-
However, we need to ensure that for numbers that have fewer digits than L, the leading zeros are not counted as digits. Our "started" flag handles that. But also, the contribution of leading zeros is not added, which is correct because they don't affect the numeric value.
-
At leaf, when started is false, we treat as number 0. But is it possible that we have started false but mask maybe non-zero? No, because we never set bits unless started true. So mask=0.
-
For number 0, condition: distinct digits = 1 (0). We treat as valid if k>=1. Good.
But what about number like 0? Actually number 0 has digit 0, so distinct=1. So for k>=1, it qualifies.
Now consider k=0? Not possible.
Now test edge case: l=r=10^18, k=10. f(10^18) sum? We'll just trust.
Now let's think about potential overflow: total_cnt and total_sum computed modulo MOD. But we also need to ensure that when we return count from leaf, it's 1 (mod). That's fine.
Now, we need to check if any state leads to double counting of numbers? No, each number corresponds to a unique path due to the DP construction.
Now, we might consider optimizing by using DP for count and sum simultaneously; but already fine.
Now, is there any issue with the use of "mask" when started is false? We treat mask=0. But when we later start, we set new_mask = mask | (1<<d). Since mask is 0, that's correct.
Now, early pruning: if started && popcount(mask) > k, return (0,0). This is correct because we can't reduce distinct digits.
But one nuance: What if started is false and we are not started yet, but we already have mask=0. That's fine.
Now, one more nuance: In the DP, we treat the mask only for digits that appear after the number has started. But what about the digit 0 after started: it is added to mask. Good.
Now, what about numbers like 1000? That's fine.
Now, check the example: 101 to 154 k=2. Let's compute manually small to verify DP.
But before that, we need to ensure that for numbers like 101, our DP will count it correctly. Let's simulate with limit=154, but we need sum from 101 to 154. So f(154)-f(100). Let's compute f(100) for k=2: sum of numbers 0..100 with at most 2 distinct digits. That includes 0..9, 11,22,33,44,55,66,77,88,99,100? 100 has digits 1,0,0 -> distinct {1,0}=2, qualifies. Also numbers like 101? but 101>100, not included. Also 110? >100. So f(100) sum includes numbers 0..9 =45, plus 11=11,22=22,33=33,44=44,55=55,66=66,77=77,88=88,99=99, and 100=100. Sum =45 + (11+22+33+44+55+66+77+88+99) + 100. The sum of two-digit repdigits: 11+22+...+99 = 11*(1+2+...+9) = 1145 = 495? Wait 1+2+...+9=45, 1145=495. So total f(100)=45+495+100=640. Now f(154) should sum numbers 0..154 with at most 2 distinct digits. We can compute manually the numbers from 101 to 154 that qualify, plus those below. But we just need the difference. According to example answer 2189. So f(154)-f(100) should be 2189. Then f(154)=2189+640=2829. Let's approximate: 0..154 sum total is 154155/2=15477.5=11935? Actually 154155/2 = 154155=23870/2=11935. Not all numbers qualify because some have 3 distinct digits? For two-digit numbers, all qualify? Actually two-digit numbers have at most 2 distinct digits, so all two-digit numbers (10-99) qualify. For three-digit numbers 100-154, some may have 3 distinct digits like 102 (1,0,2) => 3, not qualify; 103 etc. So the sum of qualifying numbers from 0..154 should be less than total sum. f(154)=? We'll compute using DP later. But trust.
Now we should test with code if possible. Since we can't run here, we need to reason about correctness.
Potential issues: The way we treat leading zeros and mask may incorrectly count numbers where the number has leading zeros that are actually part of the number? But we pad to L digits. That's standard.
Now, about the pow10_mod: we compute 10^rem % MOD. However, note that the contribution of digit d to the number is d * 10^{rem} in decimal, not modulo MOD? But we are summing modulo MOD, so using modulo is fine. However, we need to be careful about overflow when multiplying cnt_next * (d * 10^{rem}) before mod. Since cnt_next and digit_contrib are modulo MOD, the product modulo MOD is correct because we are working modulo MOD. But cnt_next is stored modulo MOD, but actual count may be huge, but multiplication modulo MOD using the count mod MOD yields the same result as (actual count mod MOD) * (digit_contrib mod MOD) mod MOD. Since sum = Σ (number) mod MOD, and each number's contribution can be broken into sum of digit contributions. The sum of contributions from all numbers can be computed modulo MOD using counts modulo MOD, because each term is multiplied by count. Since we are only interested in final sum mod MOD, using count modulo MOD is valid. Why? Because we are computing sum = Σ_i value_i mod MOD. The DP computes sum as Σ (cnt_next * (d * 10^{rem}) + sum_next). Here cnt_next is the count of numbers in the subtree. If we reduce cnt_next modulo MOD, the product (cnt_next mod MOD) * (d * 10^{rem}) mod MOD is equal to (cnt_next * (d * 10^{rem})) mod MOD because (a mod MOD * b) mod MOD = (ab) mod MOD. So it's safe. However, we must ensure that cnt_next doesn't overflow 64-bit before mod? But we are storing cnt_next modulo MOD, so it's within MOD-1. Then multiply by up to 9 * 10^{18} mod MOD, which is less than MOD^2? Actually MOD ~ 1e9, 910^18 mod MOD is some number < MOD, product < MOD^2 ~ 1e18, fits in 64-bit? MOD=998244353, MOD^2 ≈ 9.96e17, which is just under 2^63-1 (~9.22e18), so it's safe for 64-bit signed if we use unsigned? Actually 9.96e17 < 9.22e18, so safe for signed 64-bit. But we can also use modulo multiplication with (a * b) % MOD.
Thus using cnt modulo MOD is fine.
But note: In the recursion, total_cnt is computed as sum of cnt_next. Since we later multiply total_cnt by something? Not directly, but we return total_cnt modulo MOD. That is consistent.
Now one more subtlety: When we prune by popcount(mask) > k, we return (0,0). However, we need to be careful: If we are not started, mask is 0 and popcount=0 ≤k, fine. But consider numbers where we have started, and mask has popcount = k+1, we prune. That's valid because we cannot reduce distinct digits.
Now consider state where started=false but we are about to start. That's fine.
Now potential bug: In the combination step for new_started=false branch, we set contribution = sum_next. But we also need to propagate count? Actually total_cnt is incremented by cnt_next. That's fine. But total_sum adds sum_next. However, what about the fact that the digit d=0 (leading zero) does not contribute to the value, so sum_next already accounts for the value of the suffix. That's correct.
But check: For a number like "05" (value 5), at pos=0 (most significant) we choose d=0, started=false, we go to pos=1. At pos=1, choose d=5, started=true, leaf returns (1,0). Then at pos=1, contribution: new_started true, rem=0, so add cnt_next*(5*10^0)+sum_next =5. Then at pos=0, contribution: new_started false, so total_sum += sum_next (which is 5). Also total_cnt += cnt_next=1. So final sum =5. Good.
Now test for number "0" (L=2, "00"): pos=0 d=0, started false; pos=1 d=0, started false; leaf returns (1,0). pos=1: new_started false, contribution = sum_next=0. total_cnt=1. pos=0: new_started false, contribution = sum_next=0. total_sum=0. So sum 0, correct.
Now test for number "100" with L=3. Should be counted if k>=2. Let's simulate: pos0 d=1 started true, mask={1}, rem=2. pos1 d=0 started true, mask={1,0}, rem=1. pos2 d=0 started true, mask={1,0}, rem=0. leaf: mask popcount 2 <=k? if k>=2, return (1,0). Then pos2: new_started true, cnt_next=1, rem=0, digit_contrib=0? Actually d=0, digit_contrib=010^0=0, add=0, sum_next=0 => contribution=0. pos1: new_started true, cnt_next=1, rem=1, digit_contrib=010^1=0, sum_next=0 => contribution=0. pos0: new_started true, cnt_next=1, rem=2, digit_contrib=1*10^2=100, sum_next=0 => contribution=100. So sum=100, correct.
Now check for number with leading zeros that become started later: fine.
Now about the pow10_mod[rem] calculation: rem = L - pos - 1. For pos=0, rem = L-1, which is the number of digits after the most significant. That's correct because the most significant digit's place value is 10^{L-1}.
Now for numbers with fewer digits, e.g., limit=50, L=2. For number 5 (represented as 05), pos0 d=0, rem=1, but that digit's contribution not added. pos1 d=5, rem=0, contribution=5*10^0=5. So the total sum is 5. Good.
Now, there is an issue: The DP includes number 0 at the end. But when we compute f(r) - f(l-1), with l>=1, we exclude 0. Good.
Now, we need to be careful about large L: For limit up to 10^18, L could be 19 (since 10^18 is 1e18, 19 digits? Let's check: 10^18 = 1000000000000000000, that's 19 digits? Actually 10^0=1 (1 digit), 10^1=10 (2 digits), so 10^18 has 19 digits. Yes, because 10^(n) has n+1 digits. So L max = 19. So we need pow10_mod up to 18 (since rem max = 18). Actually L=19 => rem max = L-1 = 18. So pow10_mod[18] needed. We'll compute up to 19 to be safe.
Now, note: When limit is 10^18 exactly, the string length is 19. Our DP will process 19 digits. That's fine.
Now, we must be aware that the number 10^18 itself may be within the range. The DP must correctly handle the tight condition at the highest digit.
Now, about memory: cnt_memo[20][2][2][1024] is 2022*1024 = 81920 entries. Each entry is ll (8 bytes) => ~655KB. Two arrays => ~1.3MB. That's fine.
But we need to reset between solve calls. We could declare as static inside solve and memset to -1. However, note that the array size is known at compile time, we can allocate on stack? 1.3MB might be okay on stack? Usually stack limit is 1-8 MB, but it's safe to allocate as static or global to avoid stack overflow. We'll allocate as global? But we need to reset for each call. We could allocate as local using vectors or using global arrays and reinitialize with memset. Using global arrays is simpler: we can define cnt_memo and sum_memo as global and then in solve we set them to -1 with memset for the whole arrays. But the arrays are sized for maximum L (20). That's fine. However, we need to be careful because we only use L positions; but we always use indices up to L. The memo array has size 20 for pos, but we will only access up to L-1 and L. But there may be leftover entries from previous call with different L, but since we memset the entire array each time, it's fine. However, note that the mask dimension is always 1024, independent of L. So global arrays are okay.
But we need to store per call; but since we call solve twice, we need to reset in between. So we can do memset before each DFS.
But if we use global arrays, we must be careful that the DP function uses them, and they are overwritten each call. That's fine.
Now, one more nuance: The DP includes the number 0 in f(N). However, if N is 0, s="0", L=1. Then we need to handle. Let's test: solve(0). s="0", L=1. pow10_mod[0]=1, pow10_mod[1]=10? We compute up to L. L=1, we need pow10_mod[0] only? Actually rem max = L-pos-1. For pos=0, rem=0. So we need pow10_mod[0] = 1. So we can compute up to L maybe.
DP: start pos=0, tight=1, started=0, mask=0.
up = s[0] - '0' = 0.
Loop d=0 only:
new_tight = 1 and d==0 => true.
new_started = false (since d=0, started false).
new_mask = 0 (since new_started false).
Call dfs(pos=1, tight=1, started=0, mask=0). pos==L => base case.
Base: !started true, so if k>=1 return (1,0). else (0,0). k>=1 so (1,0).
Then at pos=0: cnt_next=1, sum_next=0. new_started false, so total_sum += sum_next =0. total_cnt += cnt_next =1.
Return (1,0). So f(0)=0, count=1. That's correct.
Now test solve(9) for k=1: s="9", L=1.
DP: pos=0, tight=1, started=0, mask=0.
up=9.
Loop d=0..9:
For d=0: similar to above: base returns (1,0) (since number 0 qualifies? But number 0: we need to check if k>=1, yes). So count 1, sum 0.
But careful: number 0 is included only once. That's correct because we represent "0" as one digit number; the DP with leading zeros? Actually when limit=9, L=1, the only representations are 0..9 as single-digit numbers. So 0 is included. Good.
For d=1..9: new_started true. For each d:
- new_mask = (1<<d)
- Call dfs(pos=1, tight=1 if d==9? Actually tight only true if d==up (9). For d<9, tight false; for d=9, tight true. But since pos+1 =1 = L, base case returns (1,0) if popcount(mask) <= k. For d=1..9, popcount=1 <=1 so valid.
At pos=0, rem=0, contribution = cnt_next * (d * 10^0) + sum_next = 1 * d + 0 = d.
So total sum = sum over d=0..9 contributions: d for d=1..9 plus 0 for d=0 => sum 1+2+...+9 = 45. Total count = 1 + 9 =10. So