蓝色天空.知识 · 实践 · 创造
我的收藏
数据结构与算法 教程目录 44章
数据结构与算法 / LEARN BY DOING

并查集基础

介绍并查集(Disjoint Set / Union-Find)处理动态连通性与不相交集合合并查询的核心思想、适用场景及基础 id 数组表示与初始化方式。

学完这一章,你能够

  • 介绍并查集(Disjoint Set / Union-Find)处理动态连通性与不相交集合合并查询的核心思想、适用场景及基础 id 数组表示与初始化方式。

并查集概念与大规模连通问题适用性

并查集(Union-Find / Disjoint-Set)是一种专用于管理若干不相交集合的合并(Union)与归属查询(Find)的树形抽象数据结构。其核心思想是借助一维数组维护整片森林或集合编号,以每个集合的唯一标识(树根或组号)区分连通分量,只需定位两个元素的集合标识即可判定它们是否属于同一集合。

在网络连通性检测、图论最小生成树(Kruskal)与动态等价类划分等含 N 个元素的规模化问题中,通常初始令每个元素各自独立为单元素集合,随后按需不断合并并高频查询连通状态。相比直接构建显式邻接矩阵或维护多张独立列表,并查集仅占用 O(N) 线性数组空间并能将单次操作优化至接近常数时间。

集合编号数组表示与初始化构造

最直观的入门表示方式是用整型数组 `id[]` 直接记录每个元素所属的集合编号:例如当 `0..4` 的 `id` 均为 `0`、`5..9` 的 `id` 均为 `1` 时,表示前五个元素两两连通、后五个元素两两连通;又如当偶数索引 `0、2、4、6、8` 对应组号 `0`、奇数索引 `1、3、5、7、9` 对应组号 `1` 时,分别构成两个含 5 个元素的连通集(注:原参考文后半句多写了一个“0,”,实际该奇数集合仅包含 `1、3、5、7、9` 五个元素)。构造并查集时,将数组长度设为 `n` 并令每个 `id[i] = i`,表示初始状态下没有任何元素发生合并。

基础封装类维护内部数组 `id` 与元素总数 `count`(注:原参考示例 Java 代码中类名为 `UnionFind` 而构造函数误写为 `UnionFind1`,实际编码时构造函数名须与类名严格一致)。本地 Python 实验脚本已完整验证 `id[i] = i` 初始化、两组划分映射以及连通关系的自反性、对称性与传递性。

离线校验并查集 id 数组初始化、典型集合划分与等价关系性质

含完整源码 · 126 行
展开查看收起
python
"""Offline algorithm verification lab for Chapter 34 (union-find-basic)."""
import json

VERSION = "CPython 3.12.14 offline DSA verifier (union-find-basic)"


class UnionFindInit:
    """Initial id-array representation of disjoint sets."""

    def __init__(self, n: int):
        assert n >= 0
        self.count = n
        self.id = [i for i in range(n)]

    def distinct_groups(self) -> int:
        return len(set(self.id))

    def groups_map(self) -> dict:
        groups = {}
        for elem, gid in enumerate(self.id):
            groups.setdefault(gid, []).append(elem)
        return groups


def case_union_find_init_disjoint_sets():
    uf = UnionFindInit(10)
    expected = {
        "count": 10,
        "initial_id": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        "distinct_groups": 10,
        "all_self_identified": True,
    }
    actual = {
        "count": uf.count,
        "initial_id": uf.id,
        "distinct_groups": uf.distinct_groups(),
        "all_self_identified": all(uf.id[i] == i for i in range(10)),
    }
    return {
        "name": "union_find_init_disjoint_sets",
        "summary": "验证并查集初始化后每个元素 id[i] == i,共形成 n 个互不相交的单元素集合",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_partition_representation_examples():
    # Example A: 0-4 belong to group 0, 5-9 belong to group 1
    uf_a = UnionFindInit(10)
    uf_a.id = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

    # Example B: even indices (0,2,4,6,8) belong to group 0; odd indices (1,3,5,7,9) belong to group 1
    uf_b = UnionFindInit(10)
    uf_b.id = [0 if i % 2 == 0 else 1 for i in range(10)]

    expected = {
        "example_a_groups": {0: [0, 1, 2, 3, 4], 1: [5, 6, 7, 8, 9]},
        "example_b_groups": {0: [0, 2, 4, 6, 8], 1: [1, 3, 5, 7, 9]},
        "example_a_count": 2,
        "example_b_count": 2,
    }
    actual = {
        "example_a_groups": uf_a.groups_map(),
        "example_b_groups": uf_b.groups_map(),
        "example_a_count": uf_a.distinct_groups(),
        "example_b_count": uf_b.distinct_groups(),
    }
    return {
        "name": "partition_representation_examples",
        "summary": "验证两组经典数组划分:连续段 {0..4}/{5..9} 与奇偶分组 {0,2,4,6,8}/{1,3,5,7,9}(澄清源文偶发笔误)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_disjoint_set_connectivity_check():
    uf = UnionFindInit(10)
    uf.id = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
    connected = lambda p, q: uf.id[p] == uf.id[q]
    reflexive = all(connected(i, i) for i in range(10))
    symmetric = all(connected(i, j) == connected(j, i) for i in range(10) for j in range(10))
    transitive = all(
        (not (connected(i, j) and connected(j, k))) or connected(i, k)
        for i in range(10)
        for j in range(10)
        for k in range(10)
    )
    expected = {
        "reflexive": True,
        "symmetric": True,
        "transitive": True,
        "0_and_8_connected": True,
        "0_and_1_connected": False,
        "1_and_9_connected": True,
    }
    actual = {
        "reflexive": reflexive,
        "symmetric": symmetric,
        "transitive": transitive,
        "0_and_8_connected": connected(0, 8),
        "0_and_1_connected": connected(0, 1),
        "1_and_9_connected": connected(1, 9),
    }
    return {
        "name": "disjoint_set_connectivity_check",
        "summary": "验证基于集合编号的连通判定满足等价关系的自反性、对称性与传递性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_union_find_init_disjoint_sets(),
        case_partition_representation_examples(),
        case_disjoint_set_connectivity_check(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
在 CPython 3.12.14 离线脚本中确认 10 元素初始化为 10 个独立集合、两组经典奇偶/分段划分准确且连通判定满足自反/对称/传递性。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2641.zip) ↓ 查看运行说明 ↗

本章附件与实例包

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

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

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

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

每次有效合并都会使集合总数严格减少 1,因此执行 `m` 次有效合并后剩余 `n - m` 个不相交集合(最多只能执行 `n - 1` 次有效合并)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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