并查集 size 的优化
详解基于集合元素个数 sz[] 的按规模合并优化(UnionFind3):始终将小集合根挂接到大集合根下,将树高严格压制在 O(log n) 级别。
学完这一章,你能够
- 详解基于集合元素个数 sz[] 的按规模合并优化(UnionFind3):始终将小集合根挂接到大集合根下,将树高严格压制在 O(log n) 级别。
盲目合并导致的树高膨胀与按 size 优化思路
在未优化的 Quick Union 中,对规模悬殊的两个集合执行 `union(4, 9)` 时,若不判断方向而固定把节点多、层数深的集合(根为 `8`)挂到单元素节点 `9` 下,整棵树的高度就会无谓地增加一层;随着元素规模扩大,高频上溯根节点的开销将显著上升。按规模合并(Union by Size)的改进非常直接:在合并两个根节点前先比较它们所在集合的元素个数,总是让元素更少的树根指向元素更多的树根。
sz 数组维护与按规模定向合并
实现 `UnionFind3` 时新增整型数组 `sz[]`,其中 `sz[i]` 记录以 `i` 为根的集合当前包含的元素总数,构造初始化阶段令每个 `parent[i] = i`、`sz[i] = 1`。执行 `unionElements(p, q)` 找到不同根 `pRoot` 与 `qRoot` 后:若 `sz[pRoot] < sz[qRoot]`,令 `parent[pRoot] = qRoot` 并累加 `sz[qRoot] += sz[pRoot]`;否则令 `parent[qRoot] = pRoot` 并累加 `sz[pRoot] += sz[qRoot]`。回到 `union(4, 9)` 示例,优化后单元素 `9` 会挂到根 `8` 下,树高维持不变。
O(log n) 树高上界与本地实测
数学上,每当某节点深度加 1,其所在集合的节点总数至少翻倍,因此含 n 个元素的按 `size` 并查集树高严格不超过 `floor(log2(n)) + 1`,查找与合并的最坏复杂度稳定在 O(log n)。本站离线 Python 脚本已对比复现 `union(4, 9)` 的树高差异(4 层降至 3 层),并验证了 64 元素在顺序合并下仅 2 层、最坏两两配对合并下严格不超过 7 层。
离线校验按 size 优化的 union(4,9) 方向选择与 64 元素 O(log n) 树高上界
"""Offline algorithm verification lab for Chapter 37 (union-find-size)."""
import json
VERSION = "CPython 3.12.14 offline DSA verifier (union-find-size)"
class UnionFind3:
"""Quick Union optimized by tree size (sz[])."""
def __init__(self, count: int):
self.parent = [i for i in range(count)]
self.sz = [1] * 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.sz[p_root] < self.sz[q_root]:
self.parent[p_root] = q_root
self.sz[q_root] += self.sz[p_root]
else:
self.parent[q_root] = p_root
self.sz[p_root] += self.sz[q_root]
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_size_init():
uf = UnionFind3(8)
expected = {
"parent": [0, 1, 2, 3, 4, 5, 6, 7],
"sz": [1, 1, 1, 1, 1, 1, 1, 1],
}
actual = {"parent": uf.parent, "sz": uf.sz}
return {
"name": "uf_size_init",
"summary": "验证按规模优化并查集的构造函数将 parent[i]=i 与 sz[i]=1 正确初始化",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_uf_size_weighted_union_4_9():
# Setup: tree rooted at 8 has 4 nodes (8, 3, 4, 2); node 9 is singleton
uf_size = UnionFind3(10)
uf_size.parent = [0, 1, 8, 8, 3, 5, 6, 7, 8, 9]
uf_size.sz = [1, 1, 1, 2, 1, 1, 1, 1, 4, 1]
# Naive quick union linking pRoot(8) -> qRoot(9) increases height from 3 to 4
naive_parent = list(uf_size.parent)
naive_parent[8] = 9
naive_depth_4 = 1
p = 4
while p != naive_parent[p]:
p = naive_parent[p]
naive_depth_4 += 1
# Size-weighted union(4, 9): sz[8]=4 >= sz[9]=1 -> parent[9] = 8, height remains 3!
uf_size.union_elements(4, 9)
expected = {
"naive_depth_of_4": 4,
"size_opt_parent_of_9": 8,
"size_opt_sz_of_8": 5,
"size_opt_depth_of_4": 3,
"size_opt_max_height": 3,
}
actual = {
"naive_depth_of_4": naive_depth_4,
"size_opt_parent_of_9": uf_size.parent[9],
"size_opt_sz_of_8": uf_size.sz[8],
"size_opt_depth_of_4": uf_size.depth(4),
"size_opt_max_height": uf_size.max_height(),
}
return {
"name": "uf_size_weighted_union_4_9",
"summary": "复现 union(4, 9) 场景:小集合 9 挂接到大集合根 8 下,避免高度从 3 膨胀到 4",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_uf_size_full_height_bound():
n = 64
uf = UnionFind3(n)
# Pairwise binary-tree-like merges produce exact worst-case height log2(n)+1 = 7
step = 1
while step < n:
for i in range(0, n, step * 2):
uf.union_elements(i, i + step)
step *= 2
# Sequential merges produce height 2 (star graph) instead of height 64!
uf_seq = UnionFind3(n)
for i in range(n - 1):
uf_seq.union_elements(i, i + 1)
expected = {
"pairwise_max_height": 7,
"pairwise_root_size": 64,
"sequential_max_height": 2,
"sequential_all_connected": True,
}
actual = {
"pairwise_max_height": uf.max_height(),
"pairwise_root_size": uf.sz[uf.find(0)],
"sequential_max_height": uf_seq.max_height(),
"sequential_all_connected": all(uf_seq.is_connected(0, i) for i in range(n)),
}
return {
"name": "uf_size_full_height_bound",
"summary": "在 64 元素上验证按 size 合并的树高严格受限于 O(log n)(配对合并最高 7 层、顺序合并仅 2 层)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_uf_size_init(),
case_uf_size_weighted_union_4_9(),
case_uf_size_full_height_bound(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在 CPython 3.12.14 离线脚本中确认 union(4,9) 将 9 挂至根 8 保持 3 层高,且 64 元素配对合并树高精确为 7、顺序合并仅为 2。
所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
当前源码 SHA256:1df63402654378fde11d0293ac90df4e7e85cb2687f846c93c629bf0c8fa6e54
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
ZIP SHA256:87402756c5b27515be6609b9ba86e5cc5bee78bfb0d0dc7c1dc644085112bbda
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在按 `size` 合并的并查集中,为什么当把 `pRoot` 挂到 `qRoot` 下时,只需要更新 `sz[qRoot] += sz[pRoot]` 而无需更新非根节点的 `sz` 值?
展开参考解答
因为每次合并前 `unionElements` 都会先调用 `find` 定位到两棵树的根节点,后续逻辑只会读取根节点的 `sz[root]`,非根节点的 `sz` 不再参与任何决策。