Appearance
Interesting Function -- CF 1538F
Difficulty: 1800 * Techniques: digit decomposition, floor-division counting, math Problem Link
Quick Revisit
- PROBLEM: Count total digit changes when incrementing a counter from l to r
- KEY INSIGHT: Each digit position k changes floor(r/10^k) - floor(l/10^k) times. Sum over all positions.
- TECHNIQUES: per-digit decomposition, floor-division counting, linearity of counting
- TRANSFER: "Count total X across a range" -- decompose per position/digit before reaching for DP.
First Read
Define
Constraints:
The Digit DP Trap
My first thought: "Digit changes... must be digit DP." I started thinking about states -- current position, tight constraint, carry propagation. Got 5 minutes in and the state space was growing. Carry propagation across digits is annoying.
Then I stopped. Let me think about what
Counting Digit Changes Per Position
When you increment from
The tens digit changes once every 10 increments. How many times does it change between
The hundreds digit?
In general, position
So:
That's... just arithmetic. No DP, no complicated logic.
Why This Works
Think about position
When I realized this, I actually laughed. I'd been mentally constructing a digit DP with carry states, and the answer was a three-line loop.
The Gotcha I Almost Missed
Wait -- is the ones digit formula right? Going from
Another sanity check:
One more:
The Code
cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
scanf("%d", &t);
while (t--) {
long long l, r;
scanf("%lld%lld", &l, &r);
long long ans = 0;
while (l > 0 || r > 0) {
ans += r - l;
l /= 10;
r /= 10;
}
printf("%lld\n", ans);
}
}That's the entire solution. Seven lines in the loop.
The loop is the summation in disguise: each iteration is the next power of 10. On entry to iteration ans += r - l adds the position-
The Emotional Arc
This problem taught me humility. I was so conditioned to reach for digit DP on anything with "digits" in the statement that I almost missed a pure math solution. The formula fell out once I asked the right question: "How many times does each individual digit position change?"
Decompose by position, not by number. That reframing made the problem trivial.
Transfer Lesson
- "Count total X across a range" -- before reaching for DP, ask if each position/bit/digit can be counted independently. Linearity of counting.
- Floor division counts multiples --
counts how many multiples of lie in . Fundamental identity. - If you're building a complex DP and the constraints are very generous (
) -- you're probably overthinking. Look for a closed-form or per-digit decomposition.
See also: Contribution Technique | Binary Search | Pattern Recognition Guide | Practice Ladder 1700-2100