A minimum spanning tree (MST) connects all vertices of a weighted, connected graph with the minimum total edge weight and no cycles. Kruskal and Prim are the two classic greedy algorithms.
Kruskal (sort edges, union-find)
Sort all edges by weight; add the cheapest edge that does not form a cycle.
():
parent = ((n))
():
parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
x
mst, total = [],
w, u, v (edges):
ru, rv = find(u), find(v)
ru != rv:
parent[ru] = rv
mst.append((u, v, w)); total += w
mst, total
