https://cses.fi/alon/task/2220
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
ll dp[20][11][2][2];
ll countDigits(string& s, int idx, int prevDigit, bool tight, bool leadingZeros) {
if (idx == s.size()) return 1;
if (dp[idx][prevDigit + 1][tight][leadingZeros] != -1)
return dp[idx][prevDigit + 1][tight][leadingZeros];
int limit = tight ? s[idx] - '0' : 9;
ll count = 0;
for (int d = 0; d <= limit; d++) {
if (d == prevDigit && !leadingZeros) continue;
bool nextLeadingZeros = leadingZeros && (d == 0);
bool nextTight = tight && (d == limit);
int nextPrevDigit = nextLeadingZeros ? -1 : d;
count += countDigits(s, idx + 1, nextPrevDigit, nextTight, nextLeadingZeros);
}
return dp[idx][prevDigit + 1][tight][leadingZeros] = count;
}
ll countNums(ll n) {
if (n < 0) return 0;
if (n == 0) return 1;
string s = to_string(n);
memset(dp, -1, sizeof(dp));
return countDigits(s, 0, -1, true, true);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
ll a, b;
cin >> a >> b;
cout << countNums(b) - countNums(a - 1) << endl;
return 0;
}
Top comments (0)