Time Complexity:
We will use digit DP to solve this problem.
Firstly, instead of finding the answer for the range , find the answers for the ranges and instead, and their difference will be the answer. (You'll find that one uses this technique for almost all digit DP problems).
Let be the number of good integers with digits and the -th digits is . The recurrence is and the base cases are for each . Computing DP by hand will show you that .
How do we count the number of good integers not greater than some given with digits though? We have two cases:
- The good integer has digits.
- The good integer has digits.
Any good integer falling under the first case will be counted in the answer, so this case contributes exactly to the answer.
The second case is a bit trickier though. The key observation is that any good not greater than falling under this case satisfies two conditions:
- and share a common prefix of length without any equal neighbouring digits.
- The -th digit of is less than the -th digits of .
This means that for each fixed (good) prefix of 's digits, we can count the number of good with that prefix! If the -th digits of is , then it contributes to the answer. If though, then we must also subtract from the answer to prevent two consecutive digits from being equal.
Since we can process each digit of and in time, this solution works in time.
C++
#include <bits/stdc++.h>typedef long long ll;using namespace std;ll pow_9[19]{1};ll calc(ll x) {if (x == -1) return 0;ll ans = 0;vector<int> digits;
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!