Python 3D Academyবাংলা

Bitmask DP: a whole set in one number

🌍 In real life. Three workers and three jobs, each worker with a different price for each job: who should do what, so the total is lowest? A delivery rider must visit four shops once each and come back: which round is shortest? Trying every order is n! (40,320 for 8 shops); a DP needs a state that says which items are used so far, a whole set, and a set of up to about 20 items fits in one integer's bits (Lesson 60.1).

The idea in one sentence: let bit j of an integer mask mean "item j is used"; then dp[mask] is the best answer for exactly that set, and each state grows by adding one more item, mask | (1 << j), so all 2ⁿ sets are solved in order of the numbers.

Its words:

  • mask: an integer whose 1-bits are the chosen items: 0b101 is {item 0, item 2}
  • test a bit: mask & (1 << j) is non-zero when item j is in the set
  • add an item: mask | (1 << j); count items: bin(mask).count("1")
  • full mask: (1 << n) - 1, every item used

Step by step, assigning jobs. Give the workers in order: worker 0 first, then 1, then 2. If mask holds the jobs already taken, the number of 1s says how many workers are placed, so the next worker is w = bin(mask).count("1"). From each mask, try giving worker w every free job j. Every new mask is bigger than mask, so looping masks from 0 upwards always finishes a state before it is used.

The mask 6 in binary is 110: jobs 1 and 2 are taken, job 0 is free.

Why it is correct. Any full assignment, read worker by worker, passes through masks with 1, 2, …, n bits, each one more job. dp[mask] keeps the cheapest way to reach each mask, and since how the earlier workers were placed doesn't matter to the later ones (only which jobs are taken does), the cheapest way to finish from a mask is the same whatever came before.

The travelling salesperson (Held–Karp). For a round trip, the order matters at the end too: you need to know where you are standing. So the state is dp[mask][last]: the shortest route from place 0 that visits exactly the places in mask and ends at last. Grow it by going on to an unvisited place; at the end, add the way back to 0.

What it costs, by counting. Job assignment: 2ⁿ masks × n jobs = O(n × 2ⁿ). Held–Karp: 2ⁿ × n states × n moves = O(n² × 2ⁿ): for 15 places that is about 7 million steps, against 15! ≈ 1.3 trillion orders. Still exponential: bitmask DP is for n up to about 20, which is exactly the clue in a problem's limits (Lesson 61.1).

def assign(cost):                           # cost[w][j]: worker w doing job j
    n = len(cost)
    dp = [float("inf")] * (1 << n)          # dp[mask]: cheapest way to fill the jobs in mask
    dp[0] = 0
    for mask in range(1 << n):
        w = bin(mask).count("1")            # that many workers are placed; w is next
        if w == n:
            continue
        for j in range(n):
            if not mask & (1 << j):         # job j is still free
                new = mask | (1 << j)
                dp[new] = min(dp[new], dp[mask] + cost[w][j])
    return dp[-1]


def shortest_tour(dist):                    # start and end at place 0
    n = len(dist)
    full = 1 << n
    INF = float("inf")
    dp = [[INF] * n for _ in range(full)]   # dp[mask][last]: visited mask, standing at last
    dp[1][0] = 0
    for mask in range(full):
        for last in range(n):
            if dp[mask][last] == INF:
                continue
            for nxt in range(n):
                if not mask & (1 << nxt):
                    new = mask | (1 << nxt)
                    dp[new][nxt] = min(dp[new][nxt], dp[mask][last] + dist[last][nxt])
    return min(dp[full - 1][last] + dist[last][0] for last in range(n))


print(assign([[9, 2, 7], [6, 4, 3], [5, 8, 1]]))
shops = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
print(shortest_tour(shops))
The best round of the four shops is 0 → 1 → 3 → 2 → 0: 10 + 25 + 30 + 15 = 80.

Mistakes and edge cases.

  • Testing a bit the wrong way round. if mask & (1 << j) picks jobs that are already taken; a free job is not mask & (1 << j).
  • ^ instead of |. mask ^ (1 << j) flips the bit, so on a taken job it removes it. Use | to add.
  • Operator precedence. mask & 1 << j == 0 is read as mask & ((1 << j) == 0); use brackets.
  • Too many items. 2³⁰ is about a billion states: bitmask DP stops being practical past about 20 items.
  • Forgetting the start state. In Held–Karp, dp[1][0] = 0 (only place 0 visited, standing there); starting from dp[0] lets the tour skip its start.

Quiz

  1. What does this print?

    mask = 0b1010
    print(bool(mask & (1 << 1)), bool(mask & (1 << 2)))
    print(bin(mask | (1 << 0)), bin(mask).count("1"))
  2. In the job assignment DP, how does a mask tell you which worker comes next?

    • Its number of 1-bits: that many workers are already placed
    • Its highest bit
    • The mask itself is the worker's number
  3. A problem says n ≤ 16 and asks for the best order to visit all n places. What does that limit suggest?

    • A bitmask DP over the set of visited places
    • Trying all n! orders
    • A greedy nearest-place walk
  4. assign([[9, 2, 7], [6, 4, 3], [5, 8, 1]]) should be 9, but this returns inf. Which line is wrong?

    def assign(cost):
        n = len(cost)
        dp = [float("inf")] * (1 << n)
        dp[0] = 0
        for mask in range(1 << n):
            w = bin(mask).count("1")
            if w == n:
                continue
            for j in range(n):
                if mask & (1 << j):
                    new = mask | (1 << j)
                    dp[new] = min(dp[new], dp[mask] + cost[w][j])
        return dp[-1]

Coding tasks

  1. Write assign(cost): n workers, n jobs, cost[w][j] for worker w doing job j; every worker does exactly one job. Return the lowest total cost, with a bitmask DP.

  2. Write shortest_tour(dist): the length of the shortest round trip that starts at place 0, visits every place exactly once and returns to 0. dist[a][b] may differ from dist[b][a].