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]
| Operation | Code |
|---|---|
| is w in mask? | mask >> w & 1 |
| add w | mask | (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
- Travelling Salesman Problemhardguide ready