Recently I came across several problems on different platforms that use the seemingly obscure—but actually very intuitive—idea of “Ternary Mask DP.” It’s just like bitmask DP, but instead of each bit representing two states, each digit represents three: 0, 1, or 2. The core idea is simple: convert a number into base 3, so each digit is in {0, 1, 2}. You can generalize this to any k states by using base-k.
Here’s a generalized function that encodes any integer n into an m-digit list in base k. It returns a little‑endian array of integers, but you can easily modify it to produce a string or even pack the digits into a base‑10 integer. Reverse the output if you prefer big‑endian order. (See Endianness.)
def encode_base_k(n, m, k):
nums = []
while n:
n, r = divmod(n, k)
nums.append(r)
return nums + [0] * (m - len(nums))
Below are three examples.
1) ABC 404 D – Goin’ to the Zoo
2) LC 1931 – Painting a Grid With Three Different Colors
3) CF Gym 104493 A — Gym Plates
Ternary (and, more generally, base‑k) mask DP lets you pack multi‑state decisions into a single integer, iterate cleanly over all possibilities, and handle compatibility with simple digit‑by‑digit checks. It’s a powerful pattern for grids, colorings, tilings, and any situation where each element has a few discrete states.








Auto comment: topic has been updated by grecil (previous revision, new revision, compare).
ABC 404 D – Goin’ to the Zoo
times[i] specifies how many times each zoo is visited
1931. Painting a Grid With Three Different Colors
While reading your tutorial, I started thinking about today's POTD problem and was able to come up with a solution.
Thanks man grecil :)
Auto comment: topic has been updated by grecil (previous revision, new revision, compare).