Data Structures & AlgorithmsVery hardICPC regional · bitmask DP

Problem: Find the minimum cost of a Hamiltonian tour starting and ending at city 0, with symmetric distances D = [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]. Use the bitmask DP below.

Problem: Find the minimum cost of a Hamiltonian tour starting and ending at city 0, with symmetric distances D = [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]. Use the bitmask DP below.
D = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
n = 4
INF = 10 ** 9
dp = {}
for mask in range(1, 1 << n):
    for j in range(n):
        if not (mask >> j) & 1:
            continue
        if mask == 1 << j:
            dp[(mask, j)] = 0 if j == 0 else INF
            continue
        prev = mask ^ (1 << j)
        best = INF
        for k in range(n):
            if (prev >> k) & 1 and (prev, k) in dp:
                best = min(best, dp[(prev, k)] + D[k][j])
        dp[(mask, j)] = best
print(min(dp[((1 << n) - 1, j)] + D[j][0] for j in range(n)))
What is printed?
  1. A. 85
  2. B. 75
  3. C. 80
  4. D. 90

Correct answer: C. 80

The optimal tour is 0-1-3-2-0 with cost 10 + 25 + 30 + 15 = 80. The DP over (visited set, last city) finds it in O(2^n n^2).

More Coding Interview Problems questions

Exams that ask this topic