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?- A. 85
- B. 75
- C. 80
- 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
- Problem: How many ordered outcomes of three fair six-sided dice sum to 9? Run the code. python print(sum(1 for a in range(1, 7) for b in…
- Problem: What is the Pisano period of the Fibonacci sequence modulo 10 (the length after which (F(n), F(n+1)) mod 10 repeats (0, 1))? Run…
- Problem: How many 4-digit numbers (1000 to 9999) are divisible by 11? Run the code. python print(sum(1 for x in range(1000, 10000) if x %…
- Problem: How many integers in [1, 100] have decimal digits summing to exactly 10? Run the code. python print(sum(1 for x in range(1, 101)…
- Problem: What is the minimum number of bit flips needed to make the binary string '00110' non-decreasing (all 0s then all 1s)? Run the…
- Problem: How many pairs (i < j) of 'aabab' have s[i] = 'a' and s[j] = 'b'? Run the code. python s = 'aabab' print(sum(1 for i in…