Data Structures & AlgorithmsVery hardProduct company OA

Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at city 0. What is printed?

Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at city 0. What is printed?
d = [[0, 1, 9, 2],
     [1, 0, 4, 3],
     [9, 4, 0, 8],
     [2, 3, 8, 0]]
n = 4; INF = 10**9
dp = [[INF] * n for _ in range(1 << n)]
dp[1][0] = 0
for mask in range(1 << n):
    for u in range(n):
        if dp[mask][u] == INF: continue
        for v in range(n):
            if not mask >> v & 1:
                nm = mask | 1 << v
                dp[nm][v] = min(dp[nm][v], dp[mask][u] + d[u][v])
best = min(dp[(1 << n) - 1][u] + d[u][0] for u in range(n))
greedy, cur, seen = 0, 0, {0}
while len(seen) < n:
    v = min((x for x in range(n) if x not in seen), key=lambda x: d[cur][x])
    greedy += d[cur][v]; cur = v; seen.add(v)
print(best, greedy + d[cur][0])
  1. A. 15 21
  2. B. 21 21
  3. C. 15 15
  4. D. 14 21

Correct answer: A. 15 21

dp[mask][u] = shortest path that starts at 0, visits exactly mask and ends at u – O(2ⁿ·n²) instead of O(n!). The optimal tour is 0 → 3 → 2 → 1 → 0 = 2 + 8 + 4 + 1 = 15. Nearest neighbour picks 0 → 1 (1), 1 → 3 (3), then is forced to 3 → 2 (8) and 2 → 0 (9) = 21: greedy local choices left the expensive edge 2–0 for last. Held–Karp is feasible up to n ≈ 20.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic