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))
  1. A. 7 6 21
  2. B. 7 1 21
  3. C. 8 6 21
  4. 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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic