Bitmask DP: the set of used items as the state

Video lessonComing soon

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:

cookcleanshop
Asha458
Ravi935
Meera615

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:

Two ways to reach 011
000001010011100101110111
Asha cooks, Ravi cleans: 4 + 3 = 7

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.

0shop1clean1cook
Mask 011: two chores taken, so worker 2, Meera, is next
dp[mask] = the least time when the tasks in mask go to the first popcount(mask) workers

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:

dp[mask] = min over t in mask of dp[mask without t] + cost[k − 1][t]

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:

Filling dp over the 8 masks
cookcleanshopAsha458Ravi935Meera615
cost
00004001010011100101110111
001: Asha cooks. 0 + 4 = 4
masktakenworkeroptionsdp[mask]
001cookAsha0 + 44
010cleanAsha0 + 55
011cook, cleanRavi5 + 9, 4 + 37
100shopAsha0 + 88
101cook, shopRavi8 + 9, 4 + 59
110clean, shopRavi8 + 3, 5 + 510
111all threeMeera10 + 6, 9 + 1, 7 + 510

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.

n! orders1.3 × 10¹²2ⁿ · n masks4.9 × 10⁵about 1 second
Steps at n = 15, on a scale where each mark is ten times the last

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.

9712630123
The best tour, 0 → 1 → 2 → 3 → 0, costs 15
012300971190262720331630
dist: the crossing roads are 0–2 (7) and 1–3 (6)

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:

dp[mask][last] = min over prev of dp[mask without last][prev] + dist[prev][last]

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 farends atcoston to city 3
0 → 2 → 117 + 2 = 99 + 6 = 15
0 → 1 → 229 + 2 = 1111 + 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 << 31 does not fit a 32-bit int.

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.
ProblemThe items in the maskThe shape
Partition to K Equal Sum Subsetsnumbers already placedmask alone
Minimum Number of Work Sessions to Finish the Taskstasks already donemask alone
Shortest Path Visiting All Nodesnodes already visitedmask and the current node
Find the Shortest Superstringwords already joinedmask and the last word, like TSP
Before writing a loop over every order, ask whether the rest of the problem depends on the order or only on the set. If only the set matters, it is a mask.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.