Bitmask DP: the set of used items as the state
1 Three chores, three people
Asha, Ravi and Meera share three chores at home: cooking, cleaning and shopping. Each person does exactly one chore. They are not equally quick, and the table shows how many minutes each one takes:
| cook | clean | shop | |
|---|---|---|---|
| Asha | 4 | 5 | 8 |
| Ravi | 9 | 3 | 5 |
| Meera | 6 | 1 | 5 |
We want the least total time. Giving each person their quickest free chore fails. Asha takes cooking for 4 and Ravi takes cleaning for 3. Meera is left with shopping for 5, so the total is 12. The best plan is 10: Asha cooks, Ravi shops and Meera cleans, because Meera cleans in 1 minute.
So we have to try the choices. The backtracking lesson tried every order of n items, and there are n! of them. At n = 15 that is around 1.3 × 10¹² orders. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
In code, the people are workers 0, 1 and 2, the chores are tasks 0, 1 and 2, and cost[w][t] is the time worker w takes for task t.
2 Only the set of taken chores matters
The people pick in a fixed order: Asha, then Ravi, then Meera. Each pick turns one more chore from free to taken. As in the bitmasks lesson, a set of taken chores is a mask, with cook as bit 0 on the right. In the drawing, each arrow is one pick:
Both paths end at 011: cooking and cleaning are taken, and Meera must shop. Her choice does not care who took which chore. So of the two ways to reach 011, only the cheaper one, 7, can be part of the best plan. The 14 can be dropped for good.
That is the whole idea. The drawing has 3! = 6 paths from 000 to 111, but only 2³ = 8 places to stand. For each place, we keep the best way to reach it. The state is the set of used items, held in a mask. This is bitmask DP.
The state does not need to say whose turn it is. When k chores are taken, worker k is next, and k is the mask's popcount.
The start state is dp[000] = 0: nobody has worked yet. The answer is dp[111].
3 Filling dp in increasing order
To work out dp[mask], we ask which task the last worker took. With k tasks in the mask, the last worker is k − 1. If they took task t, the others did the rest of the mask, at best dp[mask without t]. We try each t in the mask and keep the least:
In code, the mask without t is mask ^ (1 << t): the XOR turns bit t off.
Each mask reads masks with one bit fewer. Turning a 1 bit off always makes the number smaller. So when we fill masks in increasing order, 1, 2, 3 and up to 2ⁿ − 1, every slot we read is already filled.
The steps fill dp for our chores. The arrows show the slots each new value reads, and the grid marks the times it adds:
| mask | taken | worker | options | dp[mask] |
|---|---|---|---|---|
| 001 | cook | Asha | 0 + 4 | 4 |
| 010 | clean | Asha | 0 + 5 | 5 |
| 011 | cook, clean | Ravi | 5 + 9, 4 + 3 | 7 |
| 100 | shop | Asha | 0 + 8 | 8 |
| 101 | cook, shop | Ravi | 8 + 9, 4 + 5 | 9 |
| 110 | clean, shop | Ravi | 8 + 3, 5 + 5 | 10 |
| 111 | all three | Meera | 10 + 6, 9 + 1, 7 + 5 | 10 |
Row 011 is the merge from section 2: two ways in, 14 and 7, and the table keeps 7. The last row reads every mask with two chores, and Meera cleaning wins with 9 + 1 = 10.
4 The code
The code runs the formula with two loops: masks in increasing order, then each task in the mask. Every slot except dp[0] starts at the largest value its type holds. That value stands for infinity: no way found yet.
Every tab returns 10 on our chores, and 20000000000 for 20 workers who each take 10⁹ on every task. A total that big needs 64 bits.
C++
Popcount. __builtin_popcount counts the 1 bits of an int. For a long long mask, use __builtin_popcountll.
Popcount. Integer.bitCount counts the 1 bits of an int. For a long mask, use Long.bitCount.
Popcount. bit_count() needs Python 3.10 or newer. On older versions, bin(mask).count("1") gives the same count.
No built-in popcount. The short popcount loop above moves the mask right one bit at a time and adds up the bits it sees.
Popcount. bits.OnesCount comes from the math/bits package and takes a uint, so we convert the mask first.
Popcount. count_ones() returns a u32, so we turn it into a usize before using it as an index.
Popcount. BitOperations.PopCount comes from System.Numerics and takes a uint, so we cast the mask first.
Top-down works too, and it is often easier to write. Here best(mask) is the least time for the tasks not yet in mask. It tries each free task for the next worker, and a memo keyed by the mask saves each answer:
best(mask)
if mask == full - 1
return 0
if memo[mask] is filled
return memo[mask]
worker = popcount(mask)
answer = infinity
for each task t not in mask
rest = best(mask | (1 << t))
answer = min(answer, cost[worker][t] + rest)
memo[mask] = answer
return answer
The answer is best(0). The recursion goes at most n calls deep, so the stack is never a worry.
5 Cost: 2ⁿ sets instead of n! orders
There are 2ⁿ masks, and each one looks at n tasks. So the time is O(2ⁿ · n), and the table takes O(2ⁿ) space.
At n = 15, trying every order takes around 1.3 × 10¹² steps, and the masks take around 5 × 10⁵. At n = 20 the masks take around 2 × 10⁷ steps, well inside the limit, and the table holds about 10⁶ values, about 8 MB. At n = 25 it is around 8 × 10⁸ steps, and that gets TLE. So these problems keep n at about 20 or less.
6 When the last item matters too
For the chores, the next cost depends only on whose turn it is and which task they take. Some problems also depend on where we stand now. A salesman starts at city 0, visits every city exactly once, and comes back to city 0. The next step's cost depends on the city he is in. This is the travelling salesman problem, or TSP.
So the state gets a second part: the cities visited, and the last one. dp[mask][last] is the shortest path from city 0 that visits exactly the cities in mask and ends at last. To arrive at last, we came from some other city prev in the mask:
The table shows why last has to be in the state. Two paths visit cities 0, 1 and 2, and then each goes on to city 3:
| path so far | ends at | cost | on to city 3 |
|---|---|---|---|
| 0 → 2 → 1 | 1 | 7 + 2 = 9 | 9 + 6 = 15 |
| 0 → 1 → 2 | 2 | 9 + 2 = 11 | 11 + 3 = 14 |
The path ending at 1 is cheaper so far. But city 2 is closer to city 3, so the other path wins after one more step. A state without last would keep only the 9 and lose the best tour.
The start state is dp[0001][0] = 0: only city 0 is visited, and we stand there. The answer closes the tour: the least dp[1111][last] + dist[last][0]. Here that is 14 + 1 = 15.
There are 2ⁿ · n states, and each one tries n previous cities, so the time is O(2ⁿ · n²). At n = 16 that is around 1.7 × 10⁷ steps. The table holds 2ⁿ · n values. At n = 20 that is 2 × 10⁷ values, about 80 MB of 4-byte ints. So TSP problems keep n at about 16 or less.
7 Mistakes and edge cases
- Filling masks from the top down. A loop from 2ⁿ − 1 down to 1 works out dp[111] first, while dp[110], dp[101] and dp[011] still hold infinity. The answer comes out as infinity, or as a large negative number where infinity + 6 overflows. Code that pushes forward, from dp[mask] into
dp[mask | (1 << t)], needs increasing order too. - Forgetting the start state. Without dp[0] = 0, every slot stays at infinity. With every slot at 0 instead of infinity, each min stays 0, and the chores come out as 0 instead of 10.
- A dimension the mask already holds. dp[mask][worker] looks natural, but the worker is popcount(mask). At n = 20 it takes 2 × 10⁷ slots of 8 bytes, about 160 MB instead of 8 MB, and can get Memory Limit Exceeded.
- Too many items. Count 2ⁿ before choosing bitmask DP. At n = 30 the table needs 10⁹ slots, far past any memory limit, and
1 << 31does not fit a 32-bitint.
8 When to use bitmask DP
The sign is a small n, about 20 or less, and a future that depends on which items are already used, not on the order they were used in. Trying every order would be n!, so we merge the orders that reach the same set.
Then decide what the state needs beside the mask:
- Nothing. The next step's cost depends only on the set, as with the chores.
- The last item. The next step's cost depends on where we stand, as in TSP.
- A value the mask already fixes. The sum of the used items, or the next worker, follows from the mask. Work it out instead of storing it.
| Problem | The items in the mask | The shape |
|---|---|---|
| Partition to K Equal Sum Subsets | numbers already placed | mask alone |
| Minimum Number of Work Sessions to Finish the Tasks | tasks already done | mask alone |
| Shortest Path Visiting All Nodes | nodes already visited | mask and the current node |
| Find the Shortest Superstring | words already joined | mask and the last word, like TSP |
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.