"""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()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
入口文件:projects/data-structures-union-find-compress-lab/explore-union-find-compress.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-union-find-compress.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2679.zip