Three hard problems that need the best way to use every item of a small set once. The move: store the set of used items as the bits of one integer, and add only what the set cannot tell you.
You work on a back office, a settlement system and a freight planner. The three problems on this street come from all three. Each one asks for the best way to use every item of a small set exactly once, and each set has at most 16 items.
Trying every order costs n factorial. For 15 analysts that is 1,307,674,368,000 orders. A bitmask table has only 32,768 masks for the same 15 items.
The table below shows what each problem stores for a mask, which is the set of items used so far.
| Problem | The mask is | The state also needs | The next step |
|---|---|---|---|
| Assign the review cases to analysts | the analysts already used | nothing | give the next case to an unused analyst |
| Split the settlement batches into equal runs | the batches already placed | how full the open run is | place one more batch that fits |
| Shortest tour of the depots | the depots already visited | the last depot | drive to a depot not yet visited |
Read the third column. The mask says which items are used, but not always enough. The skill on this street is to add only what the mask cannot tell you.
Here is the first problem on a small case. Three review cases have skill codes 5, 3 and 6, and three analysts have codes 6, 1 and 2. Pairing a case with an analyst costs the xor of their codes.
Exercise · Predict the output: The cheapest assignment. The table best[mask] holds the lowest cost of giving the first cases, as many as the mask has bits, to exactly the analysts in the mask. What does the code print?
cases = [5, 3, 6]
analysts = [6, 1, 2]
n = 3
big = 10 ** 9
best = [big] * (1 << n)
best[0] = 0
for mask in range(1 << n):
i = bin(mask).count("1")
if i == n:
continue
for j in range(n):
if mask >> j & 1:
continue
cost = best[mask] + (cases[i] ^ analysts[j])
best[mask | 1 << j] = min(best[mask | 1 << j], cost)
print(best[(1 << n) - 1])The move has two parts.
First, store the set of used items as one integer. Item j is used when bit j of the mask is 1, so mask >> j & 1 tests it and mask | 1 << j adds it. A set of 15 items is a number below 32,768.
Second, decide what else the state needs, by asking one question: after the same set is used, can two different histories lead to different futures? For the assignment, no. The number of bits in the mask says which case comes next, so the mask is the whole state. For the tour, yes: where the van stands decides what the next trip costs, so the state is the mask and the last depot.
Let state (mask, extra) hold the best value over all histories that used exactly the items of the mask and leave the same extra information. A larger mask is built only from a smaller one, by adding one item.
Because adding an item sets one more bit, the new mask is always larger. So a loop over the masks from 0 upwards reads every state after it is final.
For the batches, the extra information is one number. The open run holds filled units. When a batch fits, the new value is (filled + batch) % target, so a run that reaches the target closes and the value returns to 0.
Test an item with a shift and a bit, and add it with or. Mask 5 plus item 1 gives mask 7.
A comparison one character wrong is enough to break the closing rule.
Exercise · Find the bug: The run that closes exactly. This checks whether the batches can be split into k runs with equal totals. It fails on a case that has a valid split. Which line is wrong?
def can_partition(batches, k):
n = len(batches)
total = sum(batches)
if total % k != 0:
return False
target = total // k
filled = [-1] * (1 << n)
filled[0] = 0
for mask in range(1 << n):
if filled[mask] < 0:
continue
for j in range(n):
if mask >> j & 1:
continue
if filled[mask] + batches[j] < target:
filled[mask | 1 << j] = (filled[mask] + batches[j]) % target
return filled[(1 << n) - 1] == 0The Academy lesson Dynamic programming from recursion turned repeated work into a table, and Knapsack kept one number per capacity. Bits and maths basics taught the shifts and masks. Here the table is indexed by a set, and three things change.
The size is exponential, so n is small. A bitmask table has 2^n masks. For the tour with 14 depots there are 229,376 states of a mask and a last depot, and 3,211,264 steps. For 30 items there are more than a billion masks, so read the limit on n before you choose.
The order of masks is the order of integers. You do not need a recursion or a topological sort. Every step adds a bit, so the loop from 0 to 2^n - 1 is already in a valid order.
The tour may revisit a depot. The van may drive through a depot it has served, so a walk is not a permutation of roads. Fill a table of shortest distances first, with Floyd-Warshall, and let the mask table use those distances. A star of four depots with unit roads needs 4 units of driving, and a table over the raw roads finds no tour at all.
For the batches, a quick test saves work: if the total is not a multiple of k, there is no split.
A star of depots has no road between outer depots. Raw roads find no tour. Shortest distances give 4 units.
Exercise · Break it: The tour over raw roads. This finds the shortest drive that calls at every depot, with a mask table over the road lengths as given. A walk may pass through a served depot. Find an input where it gives the wrong answer.
def shortest_tour(n, roads):
inf = 10 ** 9
dist = [[0 if i == j else inf for j in range(n)] for i in range(n)]
for a, b, w in roads:
dist[a][b] = min(dist[a][b], w)
dist[b][a] = min(dist[b][a], w)
best = [[inf] * n for _ in range(1 << n)]
for i in range(n):
best[1 << i][i] = 0
for mask in range(1, 1 << n):
for last in range(n):
if best[mask][last] == inf:
continue
for nxt in range(n):
if mask >> nxt & 1:
continue
cost = best[mask][last] + dist[last][nxt]
if cost < best[mask | 1 << nxt][nxt]:
best[mask | 1 << nxt][nxt] = cost
return min(best[(1 << n) - 1])Solve them in this order. The first needs only the mask. The second adds a value to the mask. The third needs the last item as well, and a table of shortest distances before the mask table starts.
Before you code each problem, write three lines: the largest n and the number of masks, what the mask means, and what else the state must hold. If n is above about 20, a bitmask is the wrong tool.
Give each problem about 40 minutes. Spend the first ten on the three lines, and fill the table by hand for three items.
Check these before you submit. Use 0 for the empty mask, and a large value for states that cannot be reached. Skip the states that are not reached before you extend them. Use the smallest input, one item, for the base case.
Checkpoint · Bitmask and state DP
Q1/5 In the assignment of cases to analysts, why is the mask alone enough as the state?
Answer: B
The mask has as many bits as there are cases already given out, so the next case is fixed by the mask. Nothing else about the history changes the future.
Q2/5 The tour over 14 depots stores the best cost for every mask and last depot. How many states is that?
Answer: C
There are 16,384 masks and 14 possible last depots, which is 229,376 states. The 14! orders are never listed.
Q3/5 Which statement explains why a loop over masks from 0 upwards is a valid order?
Answer: C
A state is built only from a smaller mask. So when the loop reaches a mask, every state that leads to it has already been visited and is final.
Q4/5 The batches are 3 and 3, and k = 2. What does a correct solution return, and what must the comparison be?
Answer: B
Each run holds one batch of 3. A strict comparison rejects a batch that reaches the target exactly, so no run could ever close and the code returns False.
Q5/5 Four depots form a star with unit roads from depot 0 to each of the others. What drive does the tour need, and why do raw roads fail?
Answer: C
The van drives out to one outer depot, back through depot 0, out to the next, back again and out to the last: 4 units. A table over raw roads allows no step between outer depots, so it finds no tour. Shortest distances make the repeat step one move.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.