并查集 rank 的优化
剖析按 size 合并在“矮胖树与瘦高树合并”反例中的不足,详解基于树层数 rank[] 的按秩合并优化(UnionFind4)及其仅在等秩时加 1 的维护法则。
学完这一章,你能够
- 剖析按 size 合并在“矮胖树与瘦高树合并”反例中的不足,详解基于树层数 rank[] 的按秩合并优化(UnionFind4)及其仅在等秩时加 1 的维护法则。
按 size 合并的反例与按 rank 合并动机
按 `size` 优化虽然已能保证对数级树高,但在特定结构下仍非局部最优。考察 `union(4, 2)` 这一反例:假设 `4` 所在集合是一棵包含 4 个节点但仅有 2 层的矮胖星型树(根为 `8`),而 `2` 所在集合是仅含 3 个节点却深达 3 层的瘦高树(根为 `7`)。若依据 `size` 将节点少的 `7` 指向节点多的 `8`,合并后树的总层数反而从 3 层增至 4 层;相反,若依据两棵树的层数(`rank`)将层数少的 `8` 指向层数多的 `7`,合并后整体高度仍保持为 3 层。这就是按秩合并(Union by Rank)的核心思想。
rank 数组维护与三分支合并规则
在 `UnionFind4` 中,用 `rank[i]` 表示以 `i` 为根的集合所对应的树层数,构造函数将所有 `parent[i] = i` 与 `rank[i] = 1` 同步初始化。合并 `pRoot` 与 `qRoot` 时分三种情况:若 `rank[pRoot] < rank[qRoot]`,令 `parent[pRoot] = qRoot`(大树高度不变,无需改动 `rank`);若 `rank[qRoot] < rank[pRoot]`,令 `parent[qRoot] = pRoot`(同样不改动 `rank`);**仅当** `rank[pRoot] == rank[qRoot]` 时,令 `parent[pRoot] = qRoot` 并执行 `rank[qRoot] += 1`。
UnionFind4 完整验证与细节说明
(注:原参考页面代码栏小标题误标为 `UnionFind3.java`,实际类定义为 `UnionFind4`。)与按 `size` 一样,按 `rank` 合并也能严格保证树高为 O(log n),且不会因为节点多而误把高树压到矮树之下。本站离线 Python 实验脚本完整复现了 `union(4, 2)` 矮胖树合并瘦高树反例(按 `size` 4 层 vs 按 `rank` 3 层)、等秩加 1 规则及 128 元素多连通分量检验。
离线复现 union(4,2) 按 size 反例并验证 UnionFind4 按 rank 合并法则
展开查看收起
"""Offline algorithm verification lab for Chapter 38 (union-find-rank)."""
import json
VERSION = "CPython 3.12.14 offline DSA verifier (union-find-rank)"
class UnionFind4:
"""Quick Union optimized by tree height upper bound (rank[])."""
def __init__(self, count: int):
self.rank = [1] * count
self.parent = [i for i in range(count)]
self.count = count
def find(self, p: int) -> int:
assert 0 <= p < self.count
while p != self.parent[p]:
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_uf_rank_init():
uf = UnionFind4(8)
expected = {
"parent": [0, 1, 2, 3, 4, 5, 6, 7],
"rank": [1, 1, 1, 1, 1, 1, 1, 1],
}
actual = {"parent": uf.parent, "rank": uf.rank}
return {
"name": "uf_rank_init",
"summary": "验证按层数 rank 优化并查集的初始化:每个元素 parent[i]=i 且初始层数 rank[i]=1",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_uf_rank_vs_size_counterexample():
# Counterexample matching union(4, 2):
# Tree A (root 8): 4 nodes, height 2 (star: 1->8, 3->8, 4->8) => size=4, rank=2
# Tree B (root 7): 3 nodes, height 3 (chain: 2->5->7) => size=3, rank=3
# Under size-based union(4, 2): sz[7]=3 < sz[8]=4 => parent[7]=8 => depth(2) becomes 4!
parent_by_size = [0, 8, 5, 8, 8, 7, 6, 7, 8, 9]
parent_by_size[7] = 8
size_depth_2 = 1
p = 2
while p != parent_by_size[p]:
p = parent_by_size[p]
size_depth_2 += 1
# Under rank-based union(4, 2): rank[8]=2 < rank[7]=3 => parent[8]=7 => max height stays 3!
uf_rank = UnionFind4(10)
uf_rank.parent = [0, 8, 5, 8, 8, 7, 6, 7, 8, 9]
uf_rank.rank = [1, 1, 1, 1, 1, 2, 1, 3, 2, 1]
uf_rank.union_elements(4, 2)
expected = {
"size_based_height_grows_to": 4,
"rank_based_parent_8": 7,
"rank_based_root_7_rank": 3,
"rank_based_max_height": 3,
}
actual = {
"size_based_height_grows_to": size_depth_2,
"rank_based_parent_8": uf_rank.parent[8],
"rank_based_root_7_rank": uf_rank.rank[7],
"rank_based_max_height": uf_rank.max_height(),
}
return {
"name": "uf_rank_vs_size_counterexample",
"summary": "复现 union(4, 2) 反例:节点多但矮的树与节点少但高的树合并时,按 size 增高至 4 层而按 rank 保持 3 层",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_uf_rank_equal_height_increment():
uf = UnionFind4(4)
# 0 and 1 both have rank 1 -> equal rank increments qRoot rank to 2
uf.union_elements(0, 1)
rank_after_eq1 = uf.rank[1]
# 2 has rank 1, 1 has rank 2 -> unequal rank keeps rank[1] == 2
uf.union_elements(2, 1)
rank_after_uneq = uf.rank[1]
# Build another rank-2 tree (3 under 3? no, need 2 nodes) -> test 6-node version
uf2 = UnionFind4(4)
uf2.union_elements(0, 1)
uf2.union_elements(2, 3)
uf2.union_elements(0, 2)
expected = {
"rank_after_equal_1_1": 2,
"rank_unchanged_after_1_2": 2,
"rank_after_equal_2_2": 3,
"height_after_equal_2_2": 3,
}
actual = {
"rank_after_equal_1_1": rank_after_eq1,
"rank_unchanged_after_1_2": rank_after_uneq,
"rank_after_equal_2_2": uf2.rank[uf2.find(0)],
"height_after_equal_2_2": uf2.max_height(),
}
return {
"name": "uf_rank_equal_height_increment",
"summary": "验证仅当两棵待合并子树的 rank 相等时新根的 rank 才加 1,高度不等时大 rank 保持不变",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_uf_rank_full_verification():
n = 128
uf = UnionFind4(n)
# Deterministic merges forming 4 connected components (mod 4)
for i in range(4, n):
uf.union_elements(i, i - 4)
roots = {uf.find(i) for i in range(n)}
expected = {
"component_count": 4,
"height_within_log2_bound": True,
"connected_0_124": True,
"connected_0_1": False,
}
actual = {
"component_count": len(roots),
"height_within_log2_bound": uf.max_height() <= 8,
"connected_0_124": uf.is_connected(0, 124),
"connected_0_1": uf.is_connected(0, 1),
}
return {
"name": "uf_rank_full_verification",
"summary": "在 128 元素按模 4 连通的完整测试中验证 UnionFind4 连通分量数与 O(log n) 树高上界",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_uf_rank_init(),
case_uf_rank_vs_size_counterexample(),
case_uf_rank_equal_height_increment(),
case_uf_rank_full_verification(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`pRoot` 子树挂到 `qRoot` 下后,该分支从 `qRoot` 算起的深度为 `1 + rank[pRoot] = 3`,仍小于等于 `qRoot` 原本已有的最大深度 `3`,因此整棵树的最大层数并未增加。