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

离线复现 union(4,2) 按 size 反例并验证 UnionFind4 按 rank 合并法则

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

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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