并查集路径压缩
详解在 find() 查根过程中实施的两种路径压缩技术——迭代跳步压缩(隔代指向祖父节点)与递归完全压缩(全路径直连根节点),并结合按 rank 合并实测树高与跳数骤降。
学完这一章,你能够
- 详解在 find() 查根过程中实施的两种路径压缩技术——迭代跳步压缩(隔代指向祖父节点)与递归完全压缩(全路径直连根节点),并结合按 rank 合并实测树高与跳数骤降。
路径压缩思想与迭代跳步压缩(Path Halving)
路径压缩(Path Compression)发生在 `find(p)` 向上寻找根节点的查询阶段:既然沿途经过的所有节点最终都归属同一个根节点,就可以顺手把非根节点向上提拉,直接削减树的高度,让后续查询愈发迅速。第一种迭代压缩(路径减半)在 `while p != parent[p]` 循环内先执行 `parent[p] = parent[parent[p]]` 再推进 `p = parent[p]`:以五节点长链 `4 -> 3 -> 2 -> 1 -> 0` 上调用 `find(4)` 为例,第一步把 `4` 改指祖父 `2`(树高减 1),第二步把 `2` 改指祖父 `0`(树高再减 1)并返回根 `0`,整棵树从 5 层瞬间压至 3 层。
递归完全路径压缩与工程权衡
若希望单次 `find(p)` 就把整条路径压成最扁平的两层星型结构,可采用第二种递归完全压缩算法:`if p != parent[p]: parent[p] = find(parent[p])`,最后 `return parent[p]`。递归回溯时,从 `p` 到根路径上的每一个中间节点都会被直接改指到最终根节点 `0`(前述 5 节点链调用 `find(4)` 后 `parent` 变为 `[0, 0, 0, 0, 0]`,树高直降至 2)。在实践开销上,迭代跳步压缩无需递归栈帧,常与完全压缩拥有相近甚至更优的常数时间表现。
结合按 rank 合并的完整实现与注意事项
将按 `rank` 合并与路径压缩结合后,并查集单次操作的均摊时间复杂度达到近乎常数的 O(alpha(n))(反阿克曼函数,对一切工程规模均不超过 5);此时 `rank` 退化为树高的上界估计,压缩路径时无需回溯重算 `rank`。(注:原参考页底部的完整类代码栏误标 `UnionFind3.java` 且 `find` 体内保留了未启用的无压缩循环而将递归压缩注释掉了;本站离线 Python 实验脚本已完整实现并实测对比无压缩、跳步压缩与递归完全压缩在 5 节点链与 256 节点树上的树高及查找跳数。)
离线追踪跳步压缩与递归完全压缩的树高变化并对比 256 元素查询跳数
展开查看收起
"""Offline algorithm verification lab for Chapter 39 (union-find-compress)."""
import json
VERSION = "CPython 3.12.14 offline DSA verifier (union-find-compress)"
class UnionFindCompress:
"""Union-Find with rank heuristic and configurable path compression mode."""
def __init__(self, count: int, mode: str = "halving"):
self.parent = [i for i in range(count)]
self.rank = [1] * count
self.count = count
self.mode = mode # "none" | "halving" | "recursive"
self.hops = 0
def find(self, p: int) -> int:
assert 0 <= p < self.count
if self.mode == "halving":
while p != self.parent[p]:
self.hops += 1
self.parent[p] = self.parent[self.parent[p]]
p = self.parent[p]
return p
if self.mode == "recursive":
if p != self.parent[p]:
self.hops += 1
self.parent[p] = self.find(self.parent[p])
return self.parent[p]
while p != self.parent[p]:
self.hops += 1
p = self.parent[p]
return p
def is_connected(self, p: int, q: int) -> bool:
return self.find(p) == self.find(q)
def union_elements(self, p: int, q: int) -> None:
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
if self.rank[p_root] < self.rank[q_root]:
self.parent[p_root] = q_root
elif self.rank[q_root] < self.rank[p_root]:
self.parent[q_root] = p_root
else:
self.parent[p_root] = q_root
self.rank[q_root] += 1
def depth(self, p: int) -> int:
h = 1
while p != self.parent[p]:
p = self.parent[p]
h += 1
return h
def max_height(self) -> int:
return max(self.depth(i) for i in range(self.count))
def case_path_compression_halving_trace():
# Chain: 4 -> 3 -> 2 -> 1 -> 0 (height 5)
uf = UnionFindCompress(5, mode="halving")
uf.parent = [0, 0, 1, 2, 3]
height_before = uf.max_height()
root = uf.find(4)
# Step 1: parent[4] = parent[3] = 2, p becomes 2
# Step 2: parent[2] = parent[1] = 0, p becomes 0 -> returns 0
expected = {
"root": 0,
"height_before": 5,
"parent_after_find_4": [0, 0, 0, 2, 2],
"height_after": 3,
}
actual = {
"root": root,
"height_before": height_before,
"parent_after_find_4": uf.parent,
"height_after": uf.max_height(),
}
return {
"name": "path_compression_halving_trace",
"summary": "追踪迭代跳步路径压缩(parent[p] = parent[parent[p]])在 4->3->2->1->0 链上执行 find(4) 后树高由 5 降至 3",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_path_compression_recursive_full_flatten():
# Same chain: 4 -> 3 -> 2 -> 1 -> 0 (height 5)
uf = UnionFindCompress(5, mode="recursive")
uf.parent = [0, 0, 1, 2, 3]
root = uf.find(4)
# Recursive compression points 1, 2, 3, 4 directly to root 0 (height 2)
expected = {
"root": 0,
"parent_after_recursive_find_4": [0, 0, 0, 0, 0],
"height_after": 2,
"all_direct_children_of_root": True,
}
actual = {
"root": root,
"parent_after_recursive_find_4": uf.parent,
"height_after": uf.max_height(),
"all_direct_children_of_root": all(uf.parent[i] == 0 for i in range(5)),
}
return {
"name": "path_compression_recursive_full_flatten",
"summary": "验证递归完全路径压缩(parent[p] = find(parent[p]))将整条路径所有节点直接挂载到根节点 0,树高压缩至 2",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_rank_with_path_compression_benchmark():
n = 256
uf_plain = UnionFindCompress(n, mode="none")
uf_halve = UnionFindCompress(n, mode="halving")
uf_recur = UnionFindCompress(n, mode="recursive")
# Pairwise merge builds an exact height-9 binomial-like tree when uncompressed
step = 1
while step < n:
for i in range(0, n, step * 2):
uf_plain.union_elements(i, i + step)
uf_halve.union_elements(i, i + step)
uf_recur.union_elements(i, i + step)
step *= 2
# Reset hop counters and query every element twice
for uf in (uf_plain, uf_halve, uf_recur):
uf.hops = 0
for _ in range(2):
for i in range(n):
uf.find(i)
expected = {
"plain_height": 9,
"recur_height_after_queries": 2,
"halve_height_le_3": True,
"compressed_fewer_hops_than_plain": True,
"all_same_connectivity": True,
}
actual = {
"plain_height": uf_plain.max_height(),
"recur_height_after_queries": uf_recur.max_height(),
"halve_height_le_3": uf_halve.max_height() <= 3,
"compressed_fewer_hops_than_plain": uf_recur.hops < uf_plain.hops and uf_halve.hops < uf_plain.hops,
"all_same_connectivity": (
uf_plain.is_connected(0, 255)
and uf_halve.is_connected(0, 255)
and uf_recur.is_connected(0, 255)
),
}
return {
"name": "rank_with_path_compression_benchmark",
"summary": "在 256 元素按 rank 合并的树上对比无压缩、跳步压缩与递归完全压缩的最终树高与查找跳数",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_path_compression_halving_trace(),
case_path_compression_recursive_full_flatten(),
case_rank_with_path_compression_benchmark(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
精确维护压缩后的真实树高会破坏 `find` 的均摊 O(alpha(n)) 复杂度;事实上只需把 `rank[]` 视为树高的上界(秩),依然能够严格保证合并平衡性与最优均摊复杂度。