Minimum Spanning Tree Problem
Find the spanning tree of weighted-graph
Theory
We greedily add the smallest unused edge
Implementation
def kruskal(adj):
edges = []
for u in adj:
for v, w in adj[u]:
edges.append((u, v, w))
edges.sort(key=lambda x: x[-1])
uf = UnionFind(len(adj))
ret = 0
for u, v, w in edges:
if uf.find(u) != uf.find(v):
uf.join(u, v)
ret += w
return ret
Runtime
Sorting the edges takes
Therefore, our runtime is dominated by the sorting, taking