Data Structures & AlgorithmsVery hardProduct company OA
Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct MSTs, number of spanning trees)?
Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct MSTs, number of spanning trees)?
from itertools import combinations
V = 5
E = [(0, 1, 1), (1, 2, 2), (0, 2, 2), (2, 3, 1), (3, 4, 3), (2, 4, 3), (1, 3, 2)]
def is_tree(es):
p = list(range(V))
def f(x):
while p[x] != x: x = p[x]
return x
for a, b, _ in es:
ra, rb = f(a), f(b)
if ra == rb: return False
p[ra] = rb
return True
ws = [sum(w for *_, w in t) for t in combinations(E, V - 1) if is_tree(t)]
print(min(ws), ws.count(min(ws)), len(ws))- A. 7 6 21
- B. 7 1 21
- C. 8 6 21
- D. 7 3 35
Correct answer: A. 7 6 21
With distinct weights the MST is unique; ties can create several. Edges of weight 1 (0–1, 2–3) are in every MST. Then exactly one weight-2 edge is needed to join {0, 1} with {2, 3} – 1–2, 0–2 or 1–3: 3 choices – and one weight-3 edge for vertex 4 – 3–4 or 2–4: 2 choices. 1 + 1 + 2 + 3 = 7 and 3 × 2 = 6 MSTs. 35 = C(7, 4) counts all subsets, not just trees (21). Kruskal finds one MST; which one depends on tie order.
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
- Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?…
- Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make…
- Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s)…
- Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost…
- 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) =…