实现说明
Kruskal 求最小生成树以函数 find、kruskal为骨架。
迭代发生在 while parent[node] != node 内部——循环之外的语句只执行一遍。
使用要点
- 直接运行文件,输出会带上标签,比如
mst weight:、edge——输出的每一行都能指回产生它的那次调用。 - 把
find当作 API:导入它,其余代码可以忽略。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 find、kruskal。
入口签名:def find(parent, node: int) -> int
核心语句
def find(parent, node: int) -> int:
while parent[node] != node:
parent[node] = parent[parent[node]] # halve the path
node = parent[node]
return node
代码示例
def find(parent, node: int) -> int:
while parent[node] != node:
parent[node] = parent[parent[node]] # halve the path
node = parent[node]
return node
def kruskal(nodes: int, edges: list[tuple[int, int, int]]) -> tuple[int, list]:
parent = list(range(nodes))
total = 0
picked: list[tuple[int, int, int]] = []
# Edges are (weight, a, b) so plain tuple order sorts by weight
for weight, a, b in sorted(edges):
root_a, root_b = find(parent, a), find(parent, b)
if root_a == root_b:
continue # this edge would close a cycle
parent[root_a] = root_b
total += weight
picked.append((weight, a, b))
if len(picked) == nodes - 1:
break
return total, picked
edges = [
(4, 0, 1),
(3, 0, 2),
(1, 1, 2),
(2, 1, 3),
(5, 2, 3),
]
total, picked = kruskal(4, edges)
print(f"mst weight: {total}")
for edge in picked:
print("edge", edge)