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)- A. 13 13 64
- B. 14 13 16
- C. 12 14 24
- 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.
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
- Recursive segment tree with children 2·node and 2·node + 1: the largest array index actually used for a given n. What is printed? python…
- Match each recurrence to its tight bound: (P) T(n) = 2T(n/2) + n log n (Q) T(n) = 2T(n/2) + n / log n (R) T(n) = T(n/2) + log n (S) T(n) =…
- A road network has n ≤ 2·10⁵ junctions and m ≤ 2·10⁵ roads; each road is either free (0) or tolled (1). You need the minimum number of…
- Which loop nests perform Θ(n log n) executions of work()? c / A / for (i = 1; i <= n; i++) for (j = i; j <= n; j += i) work(); / B / for…
- A full binary tree (every node has 0 or 2 children) has 10 internal nodes. How many leaves does it have?
- An undirected graph with V vertices and E edges is stored as adjacency lists. How many entries do all the lists hold in total?