1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 6

CAP7004 · Unit 6: Graphs

Minimum spanning trees and union-find

8 practice questions

Key points

  • Spanning tree: V-1 edges, connected, acyclic
  • Kruskal sorts edges and uses union-find
  • Prim grows from a vertex using a min-heap
  • Path compression + union by rank make union-find near O(1)

A spanning tree of a connected graph on V vertices uses V - 1 edges and connects all vertices without a cycle. The minimum spanning tree (MST) has the smallest total weight.

Kruskal's algorithm (greedy, edges):

  1. Sort edges by weight.
  2. Take each edge if it connects two different components (no cycle); skip otherwise.
  3. Stop at V - 1 edges.

Time O(E log E) (the sort dominates).

Prim's algorithm (greedy, vertices): grow one tree from a start vertex, always adding the cheapest edge leaving the tree (uses a min-heap). Time O(E log V).

Worked example: edges A-B 1, A-C 2, B-C 3, C-D 4, B-D 5. Kruskal takes A-B (1), A-C (2), skips B-C (it would make a cycle), takes C-D (4): total 7 with 3 edges. Prim from A also gives 7.

Union-find (disjoint set union) tracks components for Kruskal: find(x) returns the set representative; union(a, b) merges sets. With path compression and union by rank each operation is almost O(1) (amortized inverse Ackermann).

Properties: if all edge weights are distinct the MST is unique. The MST of a graph on V vertices always has exactly V - 1 edges.

Exam pitfall: MST minimises total weight, not the distance between particular vertices (that is shortest path).

Try two questions

Question 1 · Tier 3, Apply

Edges A-B 1, A-C 2, B-C 3, C-D 4, B-D 5. The weight of the minimum spanning tree is:

  1. 10
  2. 7
  3. 6
  4. 8
Show the answer

B. Kruskal picks [('A', 'B', 1), ('A', 'C', 2), ('C', 'D', 4)]: total 7.

Question 2 · Tier 2, Understand

Prim's algorithm grows the tree by repeatedly adding:

  1. The cheapest edge leaving the current tree
  2. The heaviest edge not forming a cycle
  3. The cheapest edge in the whole graph
  4. A random edge
Show the answer

A. At each step the lightest edge that crosses from the tree to outside is safe.