Kruskal's algorithm builds the MST greedily: sort every edge by weight, then walk through them cheapest-first, adding an edge only when it links two currently separate components (using the DSU from Step 1). Skipping edges that would form a cycle guarantees the minimum total cost.
Implement kruskal(n, edges):
Real use: this total is the minimum cabling budget needed to connect the whole network.
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
def connected(self, a, b):
return self.find(a) == self.find(b)
def kruskal(n, edges):
"""Return the total weight of the MST using Kruskal's algorithm."""
# TODO: sort edges by weight, union non-cyclic ones, sum their weights
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Kruskal's algorithm builds the MST greedily: sort every edge by weight, then walk through them cheapest-first, adding an edge only when it links two currently separate components (using the DSU from Step 1). Skipping edges that would form a cycle guarantees the minimum total cost.
Implement kruskal(n, edges):
Real use: this total is the minimum cabling budget needed to connect the whole network.
Press Run Tests or ββ© to check your solution.