Last active
August 16, 2025 21:39
-
-
Save siavashk/c396c5fce215d51dd7d8b33805edf8b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# UnionFind is defined in https://gist.github.com/siavashk/fef678f9f2ef17fdc6cff917922bf4ba | |
# Augment the union function to return True for new connections | |
def kruskal(edges: list[tuple[int, int, int]]): | |
""" | |
Edges: list of edge in (weight, start, end]) format | |
""" | |
edges.sort() | |
uf = UnionFind() | |
for _, x, y in edges: | |
uf.add(x) | |
uf.add(y) | |
total_cost = 0 | |
mst_edges = [] | |
for w, x, y in edges: | |
if uf.union(x, y): | |
total_cost += w | |
mst_edges.append([w, x, y]) | |
if len(mst_edges) == len(uf.parent) - 1: | |
break | |
return total_cost, mst_edges |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment