Sub topic 10
Compact Subset States with Bitmasks
This chapter assumes you know bottom-up tabulation, Big-O space analysis, and Python's bitwise operators (&, |, <<). It builds on the earlier chapter about removing state dimensions you can derive.
When the State Is a Subset
Some problems need to track which items from a set have already been used. The assignment problem is a standard example. There are n workers and n jobs, and cost[i][j] is the cost of giving job j to worker i. You want to give each worker exactly one job at the lowest total cost.
A first attempt at the state is "worker i is next, and this set of jobs is already taken." Storing the set as a Python set or frozenset as a dictionary key works. It is slow, though, and each key costs hundreds of bytes. A bitmask is a cheaper option. It is an integer whose bit j is 1 when job j is taken. With n jobs, every subset maps to one integer in 0 .. 2^n - 1, so the table can be a flat list indexed by the mask.
| Operation | Bitmask expression | Column |
|---|---|---|
| Is job `j` taken? | `mask & (1 << j)` | |
| Take job `j` | `mask \ | (1 << j)` |
| All jobs taken | `(1 << n) - 1` | |
| Number taken | `bin(mask).count('1')` |
Dropping the Worker Dimension
The state (i, mask) gives a table of n * 2^n entries. Workers are assigned in order 0, 1, 2, and so on, so when the mask has k bits set, exactly workers 0 .. k-1 have jobs. That means the next worker is i = popcount(mask). You can compute i from the mask, so it doesn't need its own dimension, and the table shrinks to 2^n entries.
def min_assignment_cost(cost):
n = len(cost)
INF = float('inf')
dp = [INF] * (1 << n)
dp[0] = 0
for mask in range(1 << n):
if dp[mask] == INF:
continue
i = bin(mask).count('1')
if i == n:
continue
for j in range(n):
if not mask & (1 << j):
nxt = mask | (1 << j)
dp[nxt] = min(dp[nxt], dp[mask] + cost[i][j])
return dp[(1 << n) - 1]
cost = [[9, 2, 7],
[6, 4, 3],
[5, 8, 1]]
print(min_assignment_cost(cost)) # 9Each transition sets one more bit, so nxt > mask always holds. Looping over masks in increasing numeric order therefore finishes every state before any state that reads from it.
Cost and Limits
Dropping the worker dimension saves a factor of n in memory. At n = 20 the table goes from about 21 million entries to about 1 million. A Python list stores an 8-byte pointer per slot, so that is roughly 168 MB versus 8 MB. Time stays at O(n * 2^n), because each mask still tries all n jobs.
Common mistakes:
- Operator precedence.
mask & 1 << jworks because<<binds tighter than&. Inmask & (1 << j) == 0, though,==binds tighter than&, so Python evaluatesmask & ((1 << j) == 0). Add parentheses or usenot. - Wrong iteration order. If a transition clears bits, numeric order no longer finishes the states that are read first.
- Keeping a derivable index. If a coordinate can be computed from the mask, storing it multiplies memory with no benefit.
Exercise
Using the cost matrix above, what is dp[0b011], and which assignments does it compare?
Show answer
dp[0b011] = 8. Mask 0b011 means jobs 0 and 1 are taken by workers 0 and 1. The two options are worker 0 → job 0 and worker 1 → job 1 (9 + 4 = 13), or worker 0 → job 1 and worker 1 → job 0 (2 + 6 = 8). The minimum is 8.
Exercise
Suppose tasks could be assigned to workers in any order, so the worker index could not be derived from the mask. What state would you need, and how big would the table be?
Show answer
You would need both the worker index and the mask as the state, (i, mask), which gives n * 2^n entries. You can drop i only because a fixed assignment order makes i equal to popcount(mask).