[Tutorial] Ternary Mask Dynamic Programming

Правка en3, от grecil, 2025-12-09 00:34:33

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

Solution
Code

2) LC 1931 – Painting a Grid With Three Different Colors

Solution
Code

3) CF Gym 104493 A — Gym Plates

Solution
Code

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.

Теги tutorial, dynamic programming, bitmask

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en3 Английский grecil 2025-12-09 00:34:33 2123 Tiny change: 'od\n```\n<spoiler>\n' -> 'od\n```\n</spoiler>\n'
en2 Английский grecil 2025-05-18 16:04:52 0 (published)
en1 Английский grecil 2025-05-18 16:03:44 4753 Initial revision (saved to drafts)