We are going to write the code for Kruskal's algorithm because the question specifically mentions that Disjoint Set Union is crucial for Kruskal's algorithm.
However, note that the question asks: "write the code for one of these algorithms". We can choose either, but let's do Kruskal's.
Steps for Kruskal's algorithm:
- Sort all the edges in non-decreasing order of their weight.
- Initialize an empty set for the MST and a Disjoint Set Union (DSU) structure with each vertex as a separate set.
- Iterate through the sorted edges and for each edge (u, v, weight):
a. If u and v are in different sets (i.e., no cycle is formed), include the edge in the MST and union the sets of u and v.
b. If they are in the same set, skip to avoid cycle.
- Stop when we have V-1 edges (if the graph is connected) or when we run out of edges.
We assume the graph is given as a list of edges, each edge represented as (u, v, weight). The vertices are numbered from 0 to n-1.
We'll implement:
- A DSU class with find and union operations (with path compression and union by rank for efficiency).
- The main function that takes the number of vertices and the list of edges and returns the MST (as a list of edges) and the total weight.
Note: The graph might not be connected. In that case, we return the MST for each connected component? Actually, Kruskal's will produce a minimum spanning forest.
However, the problem says "find the Minimum Spanning Tree", so if the graph is not connected, we are actually finding a minimum spanning forest (one tree for each connected component). But note: a tree by definition is connected. So if the graph is disconnected, we get a forest.
We'll assume the graph might be disconnected and return the MST edges and total weight of the forest.
But note: the number of edges in the MST of a connected graph with n vertices is n-1. For a disconnected graph with c components, the total number of edges in the minimum spanning forest is n - c.
Let's code accordingly.
Steps in code:
- Sort the edges by weight.
- Initialize DSU for n vertices.
- For each edge in sorted order:
if find(u) != find(v):
add edge to MST
union(u, v)
add weight to total
- Return the MST edges and total weight.
However, note: the problem does not specify the output format. We'll return a tuple: (list of edges in MST, total weight).
But note: the input edges might be given in any order, and we are returning the edges that form the MST.
Let's code accordingly.
We'll also note that the graph might have multiple edges between the same pair of vertices? Our algorithm will consider the smallest one first and then skip the rest because they will be in the same set after the first one is taken. So it's okay.
Implementation:
We assume the graph is undirected. The edge (u, v) is the same as (v, u). We are given a list of edges, so we don't have to worry about direction.
Let's write the DSU class first.
Minimum Spanning Tree (MST)
A Minimum Spanning Tree (MST) of a connected, undirected, weighted graph is a subset of edges that:
- Connects all vertices (spanning tree).
- Has no cycles (tree property).
- Minimizes the total edge weight.
If the graph is disconnected, MSTs exist for each connected component (forming a minimum spanning forest).
Kruskal's Algorithm
Idea: Sort edges by weight (ascending) and greedily add edges that connect disjoint components without forming cycles.
Steps:
- Sort all edges by weight.
- Initialize each vertex as a separate component (using Disjoint Set Union/Union-Find).
- Iterate through sorted edges:
- If edge connects two different components (find operation), add it to MST and merge components (union operation).
- Stop when MST has (V-1) edges (or all vertices connected).
Crucial Data Structure: Disjoint Set Union (Union-Find) with path compression and union by rank for near-constant amortized time complexity.
Time Complexity: (O(E \log E)) (dominated by sorting) with efficient DSU.
Prim's Algorithm
Idea: Grow the MST incrementally from a starting vertex by always adding the cheapest edge connecting the current MST to an outside vertex.
Steps:
- Start with an arbitrary vertex.
- Maintain a min-priority queue of edges with one endpoint in the MST and the other outside.
- Repeatedly extract the minimum-weight edge from the queue:
- If the edge leads to an unvisited vertex, add it to MST and insert new edges from that vertex into the queue.
- Use a visited array to track included vertices.
Crucial Data Structure: Min-heap/Priority Queue (typically binary heap or Fibonacci heap) for efficient edge extraction.
Time Complexity:
- With binary heap: (O(E \log V))
- With Fibonacci heap: (O(E + V \log V))
Code Implementation (Kruskal's Algorithm)
from typing import List, Tuple
class DisjointSetUnion:
def __init__(self, n: int):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x: int) -> int:
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # Path compression
return self.parent[x]
def union(self, x: int, y: int) -> bool:
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False # Already in same set
# Union by rank
if self.rank[xr] < self.rank[yr]:
self.parent[xr] = yr
elif self.rank[xr] > self.rank[yr]:
self.parent[yr] = xr
else:
self.parent[yr] = xr
self.rank[xr] += 1
return True
def kruskal_mst(n: int, edges: List[Tuple[int, int, int]]) -> Tuple[List[Tuple[int, int, int]], int]:
"""
Find Minimum Spanning Tree using Kruskal's algorithm.
Args:
n: Number of vertices (0 to n-1)
edges: List of (u, v, weight) tuples
Returns:
(mst_edges, total_weight) where mst_edges is list of edges in MST.
Returns empty MST and weight 0 if graph is disconnected (forest).
"""
# Sort edges by weight (ascending)
edges.sort(key=lambda x: x[2])
dsu = DisjointSetUnion(n)
mst_edges = []
total_weight = 0
edges_used = 0
for u, v, w in edges:
if dsu.union(u, v): # Edge connects two components
mst_edges.append((u, v, w))
total_weight += w
edges_used += 1
if edges_used == n - 1: # MST complete for connected component
break
return mst_edges, total_weight
# Example usage:
if __name__ == "__main__":
# Graph: 4 vertices, edges (u, v, weight)
edges = [
(0, 1, 1),
(0, 2, 4),
(1, 2, 2),
(1, 3, 5),
(2, 3, 3)
]
n = 4
mst, weight = kruskal_mst(n, edges)
print("MST edges:", mst)
print("Total weight:", weight)
# Output:
# MST edges: [(0, 1, 1), (1, 2, 2), (2, 3, 3)]
# Total weight: 6
Key Notes:
- The code handles disconnected graphs (returns a minimum spanning forest).
- DSU operations (
find, union) are nearly (O(\alpha(n))) (inverse Ackermann) due to optimizations.
- Sorting dominates time complexity: (O(E \log E)).
- For dense graphs, Prim's with adjacency matrix may be preferable; for sparse graphs, Kruskal's is often simpler.