蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Quick Union 父指针森林、查根合并与顺序链接退化链

PYTHONWindows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。explore-union-find-quick-merge.py
explore-union-find-quick-merge.py165 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。

入口文件:projects/data-structures-union-find-quick-merge-lab/explore-union-find-quick-merge.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-union-find-quick-merge.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2681.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习