A Few Notes on Digit DP
Notes on the digit DP technique, with code for five example problems from LightOJ, HDU, and SPOJ.
Machine-translated from the Chinese original.
Digit DP is used to solve problems of the following form: Given a closed interval , find the total number of integers in this interval that satisfy some condition.
Digit DP is a fairly simple idea: it enumerates the possibilities digit by digit, and adds a cache for the common part. For problems with multiple test cases, the cache does not need to be cleared between test cases (because the cache targets the general case, while boundary cases are counted directly without caching, so the cache can be shared).
Personally, I feel that implementing digit DP with
memoized DFSis a bit easier than with plainDP. One property of digit DP is thatdfs(x, y, z)is fully determined once the triple(x, y, z)is fixed, so it can be cached. But at boundary cases the cache is not general, so those are counted directly.What digit DP does is this: brute-force counting enumerates as , with no shared part, but digit DP counts by fixing each digit one at a time, which gives it the advantage that a large amount of repetition appears and can be optimized away.
[LightOJ 1140] How Many Zeroes?
Problem
Find the total number of digits across the decimal representations of the numbers in the interval .
[HDU 2089] No 62
Problem
Find the count of numbers in the interval whose decimal representation contains neither consecutive nor the digit .
[HDU 3555] Bomb
Problem
Find the count of numbers in the interval whose decimal representation contains consecutive .
See the comments.
[SPOJ BALNUM] Balanced Numbers
Problem
A positive integer is considered a balanced number if:
- every even digit appears an odd number of times in its decimal representation, and
- every odd digit appears an even number of times in its decimal representation.
That translation above is pretty much garbage, just get the gist.
For example, , , , and are balanced numbers, while , , and are not.
Given an interval , find the count of balanced numbers in it.
See the comments.
[SPOJ MYQ10] Mirror Number
Problem
A mirror number is a palindrome containing only the digits , , and .
Find how many mirror numbers are in .
The data range is , so the input has to be stored in a character array. Also remember to special-case whether itself is a palindrome.
If you need to compile and run this, you can go to the Gist backup to copy the common header.
If your compiler does not support C++11, change constexpr to const.
