Data Structures & AlgorithmsVery hardProduct company OA

Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost, greedy cost, number of memoised states)?

Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost, greedy cost, number of memoised states)?
from functools import lru_cache
cost = [[9, 2, 7, 8],
        [6, 4, 3, 7],
        [5, 8, 1, 8],
        [7, 6, 9, 4]]
n = 4
@lru_cache(None)
def go(i, mask):
    if i == n: return 0
    return min(cost[i][j] + go(i + 1, mask | 1 << j) for j in range(n) if not mask >> j & 1)
used, g = set(), 0
for i in range(n):
    j = min((j for j in range(n) if j not in used), key=lambda j: cost[i][j]); used.add(j); g += cost[i][j]
print(go(0, 0), g, go.cache_info().currsize)
  1. A. 13 13 64
  2. B. 14 13 16
  3. C. 12 14 24
  4. D. 13 14 16

Correct answer: D. 13 14 16

The worker index equals the number of set bits in mask, so the state is effectively just the mask: 2⁴ = 16 states, O(2ⁿ·n) total instead of n!. Optimum 13: 0→1 (2), 1→0 (6), 2→2 (1), 3→3 (4). Greedy takes the cheapest free job per row: 2, 3, then worker 2 must take job 0 (5), worker 3 job 3 (4) = 14 – an early cheap choice blocks a cheaper one later. 64 counts (i, mask) pairs as if they were independent.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic