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

离线校验按 size 优化的 union(4,9) 方向选择与 64 元素 O(log n) 树高上界

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

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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