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])- A. 15 21
- B. 21 21
- C. 15 15
- 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped)…
- BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])? python from collections import…
- Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E…
- AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)? python class…
- B-tree with minimum degree t = 2 (a 2-3-4 tree, at most 3 keys per node) using the single-pass insertion that splits every FULL node on…
- Building a min-heap from [9, 8, 7, 6, 5, 4, 3]: (a) seven sift-up insertions, (b) bottom-up heapify. What is printed (heaps and swap…