并查集快速合并
详解基于 parent 父指针森林的 Quick Union 并查集(UnionFind2):通过树根代表集合将合并简化为单条指针修改,并分析 O(h) 复杂度与链式退化风险。
学完这一章,你能够
- 详解基于 parent 父指针森林的 Quick Union 并查集(UnionFind2):通过树根代表集合将合并简化为单条指针修改,并分析 O(h) 复杂度与链式退化风险。
核心操作抽象与 parent 父指针森林模型
并查集对外核心支持三个接口:`union(p, q)` 合并两元素所属集合、`find(p)` 查询元素所属集合标识、`isConnected(p, q)` 判断两元素是否连通。为解决上一节 Quick Find 每次合并都要全表扫描 O(n) 的瓶颈,Quick Union 改用“子节点指向父节点”的森林模型来表示集合。
在数组 `parent[]` 中,`parent[i]` 存储元素 `i` 的父节点编号,而集合根节点的特点是 `parent[root] == root`(指向自身)。初始时每个元素 `parent[i] = i` 各自独立成树;当执行 `union(4, 3)` 时,只需修改单条父指针 `parent[4] = 3` 使节点 `4` 挂到节点 `3` 之下(节点 `3` 若指向 `2`、根节点 `2` 指向自己,则 `4、3、2` 属于同一棵树)。
查根连通判定与根节点对接合并
判定两个元素是否连通,只需比较它们顺着父指针回溯到的根节点是否相同——例如节点 `4` 与节点 `9` 的根节点同为 `8`,即判定相连。合并两个元素所属集合时,也无需逐一修改组内成员,只需分别找到两者的根节点并将其中一个根节点指向另一个根节点(例如将 `6` 的根 `5` 指向 `4` 的根 `8`),即可一步把整棵子树并入目标集合。
在实现 `UnionFind2` 时,`find(p)` 通过 `while p != parent[p]: p = parent[p]` 不断上溯直至根节点,时间复杂度为 O(h)(h 为当前树高);`unionElements(p, q)` 先求 `pRoot = find(p)` 与 `qRoot = find(q)`,不同则置 `parent[pRoot] = qRoot`,同样为 O(h)。
UnionFind2 完整实现与树高退化检验
值得注意的是,未加约束地固定令 `parent[pRoot] = qRoot` 可能在顺序合并 `union(0, 1), union(1, 2), ...` 时构造出高度等于 n 的退化长链,使 O(h) 重新退化为 O(n)。本站离线 Python 实验脚本完整复现了 `union(4, 3)`、共根 `8` 判定、根 `5` 挂接根 `8` 以及 16 元素链式退化高度为 16 的现象,为后续 `size`/`rank` 优化提供直观实证。
离线校验 Quick Union 父指针森林、查根合并与顺序链接退化链
"""Offline algorithm verification lab for Chapter 36 (union-find-quick-merge)."""
import json
VERSION = "CPython 3.12.14 offline DSA verifier (union-find-quick-merge)"
class UnionFind2:
"""Quick Union: parent-pointer forest with O(h) find and O(h) union."""
def __init__(self, count: int):
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
self.parent[p_root] = 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_quick_union_parent_forest_init():
uf = UnionFind2(10)
init_parent = list(uf.parent)
uf.union_elements(4, 3)
expected = {
"init_parent": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"after_union_4_3_parent_4": 3,
"after_union_4_3_parent_3": 3,
"connected_4_3": True,
}
actual = {
"init_parent": init_parent,
"after_union_4_3_parent_4": uf.parent[4],
"after_union_4_3_parent_3": uf.parent[3],
"connected_4_3": uf.is_connected(4, 3),
}
return {
"name": "quick_union_parent_forest_init",
"summary": "验证 parent 数组初始化森林结构及 union(4, 3) 仅修改单条父指针 parent[4] = 3",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_quick_union_find_root():
uf = UnionFind2(10)
# Build tree rooted at 8 containing 4 and 9 (matches chapter example)
uf.union_elements(4, 3)
uf.union_elements(3, 8)
uf.union_elements(9, 8)
expected = {
"root_4": 8,
"root_9": 8,
"root_8_is_self": True,
"connected_4_9": True,
"depth_4": 3,
}
actual = {
"root_4": uf.find(4),
"root_9": uf.find(9),
"root_8_is_self": uf.parent[8] == 8,
"connected_4_9": uf.is_connected(4, 9),
"depth_4": uf.depth(4),
}
return {
"name": "quick_union_find_root",
"summary": "验证 find(p) 沿 parent 指针逐层上溯直至 parent[p] == p 根节点,确认节点 4 与 9 共根 8",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_quick_union_merge_roots():
uf = UnionFind2(10)
# Tree A rooted at 8: 4 -> 3 -> 8, 9 -> 8
uf.union_elements(4, 3)
uf.union_elements(3, 8)
uf.union_elements(9, 8)
# Tree B rooted at 5: 6 -> 5
uf.union_elements(6, 5)
# Connect 6 and 4 -> links root 5 to root 8
uf.union_elements(6, 4)
expected = {
"parent_of_5_now_8": 8,
"root_6": 8,
"connected_6_9": True,
"connected_6_0": False,
}
actual = {
"parent_of_5_now_8": uf.parent[5],
"root_6": uf.find(6),
"connected_6_9": uf.is_connected(6, 9),
"connected_6_0": uf.is_connected(6, 0),
}
return {
"name": "quick_union_merge_roots",
"summary": "验证合并节点 6(根 5)与节点 4(根 8)时仅将根 5 指向根 8,实现整棵子树合并",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_quick_union_chain_degeneration():
n = 16
uf = UnionFind2(n)
# Worst-case sequential linking creates a degenerate chain of height n
for i in range(n - 1):
uf.union_elements(i, i + 1)
expected = {
"root_0": 15,
"max_height": 16,
"depth_0": 16,
"all_connected": True,
}
actual = {
"root_0": uf.find(0),
"max_height": uf.max_height(),
"depth_0": uf.depth(0),
"all_connected": all(uf.is_connected(0, i) for i in range(n)),
}
return {
"name": "quick_union_chain_degeneration",
"summary": "验证未优化的 Quick Union 按顺序合并时退化为高度 O(n) 的单链表,引出后续按 size/rank 优化的动机",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_quick_union_parent_forest_init(),
case_quick_union_find_root(),
case_quick_union_merge_roots(),
case_quick_union_chain_degeneration(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在 CPython 3.12.14 离线脚本中确认 union(4,3) 单指针修改、4/9 共根 8、根 5 挂接根 8,以及 16 元素顺序合并退化至树高 16。
所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
当前源码 SHA256:f5943a34b291719c3fa4781f760c03893c3183052b93cb1745aa90c896cb9db3
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
ZIP SHA256:8b64a87ee624a710fd01b46fad2d15e879544bc5ec834ac2742e6421cd1ac545
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Quick Union 中,为什么执行 `union(p, q)` 时必须连接 `pRoot` 和 `qRoot`(`parent[pRoot] = qRoot`),而不能直接写 `parent[p] = q`?
展开参考解答
若直接修改 `parent[p] = q`,`p` 原本在树中的祖先分支会与 `p` 及其子树彻底断开,破坏原有连通关系并导致集合错误分裂;只有连接两棵树的根节点才能完整保留两个集合的全部连通边。