Learn / Dynamic programming

Bitmask DP

When the state must remember which of a small set of items have been used, store it as a bitmask: bit i is 1 when item i is used. With n up to about 20, the 2ⁿ masks fit in memory. The travelling salesman DP keeps (mask of visited cities, current city).

How to recognise it

  • A set of up to about 20 items, and which have been used matters.
  • Visiting every city, assigning every task, covering every element.
  • Brute force over permutations would be n!.

Sets as numbers

dp[1 << 0][0] = 0                         # start at city 0
for mask: for v in mask: for w not in mask:
    dp[mask | 1 << w][w] = min(..., dp[mask][v] + cost[v][w])
answer = min over v of dp[all][v] + cost[v][0]
OperationCode
is w in mask?mask >> w & 1
add wmask | (1 << w)
all items(1 << n) - 1

Common mistakes

  • Using bitmasks for n much larger than 20.
  • Forgetting the cost of returning to the start.

Problems

0 of 1 solved

Check yourself

How many states does TSP's DP have for n cities?

How do you mark city w as visited?

Why is 2ⁿ × n² better than n!?