并查集实现(路径压缩)

并查集 Union Find 算法

定义

并查集(Disjoint-Set)是一种可以动态维护若干个不重叠的集合,并支持合并与查询两种操作的一种数据结构。

基本操作

  1. 合并(Union):合并两个集合。
  2. 查询(Find):查询元素所属集合。

具体实现

我们建立一个数组father_dict字典表示一个并查集,father_dict[i]表示i的父节点。并且设置一个size_dict字典,size_dict[i]表示i的后代节点的个数,包括其本身。

初始化:

每一个点都是一个集合,因此自己的父节点就是自己father_dict[i]=i,size_dict[i]=1.

查询:

每一个节点不断寻找自己的父节点,若此时自己的父节点就是自己,那么该点为集合的根结点,返回该点。

合并:

合并两个集合只需要合并两个集合的根结点,size_dict大吃小,为了尽可能的降低树高。

路径压缩:

实际上,我们在查询过程中只关心根结点是什么,并不关心这棵树的形态(有一些题除外)。因此我们可以在查询操作的时候将访问过的每个点都指向树根,这样的方法叫做路径压缩,单次操作复杂度为O(logN)。

路径压缩

具体实现:

python 复制代码
    def Find(self, x):
        root = self.father_dict[x]
        # 路径压缩
        while root != self.father_dict[root]:
            root = self.father_dict[root]
        while x != root:
            x, self.father_dict[x] = self.father_dict[x], root
        return root

防止树的退化

python 复制代码
        if self.size_dict[x_father] > self.size_dict[y_father]:
            self.father_dict[y_father] = x_father
            self.size_dict[x_father] += self.size_dict[y_father]
        else:
            self.father_dict[x_father] = y_father
            self.size_dict[y_father] += self.size_dict[x_father]

具体实现代码

python 复制代码
class UnionFindSet:
    def __init__(self, n):
        self.father_dict = {}
        self.size_dict = {}
        for i in range(n):
            self.father_dict[i] = i
            self.size_dict[i] = 1

    def Union(self, x, y):
        x_father = self.Find(x)
        y_father = self.Find(y)
        if x_father == y_father:
            return
        if self.size_dict[x_father] > self.size_dict[y_father]:
            self.father_dict[y_father] = x_father
            self.size_dict[x_father] += self.size_dict[y_father]
        else:
            self.father_dict[x_father] = y_father
            self.size_dict[y_father] += self.size_dict[x_father]

    def Find(self, x):
        root = self.father_dict[x]
        # 路径压缩
        while root != self.father_dict[root]:
            root = self.father_dict[root]
        while x != root:
            x, self.father_dict[x] = self.father_dict[x], root
        return root
相关推荐
__lost11 分钟前
Python图像变清晰与锐化,调整对比度,高斯滤波除躁,卷积锐化,中值滤波钝化,神经网络变清晰
python·opencv·计算机视觉
pystraf12 分钟前
UOJ 228 基础数据结构练习题 Solution
数据结构·c++·算法·线段树
ErizJ14 分钟前
Golang | 迭代器模式
开发语言·golang·迭代器模式
海绵波波10716 分钟前
玉米产量遥感估产系统的开发实践(持续迭代与更新)
python·flask
牙痛不能吃糖,哭18 分钟前
C++面试复习日记(8)2025.4.25,malloc,free和new,delete的区别
开发语言·c++
海底火旺21 分钟前
破解二维矩阵搜索难题:从暴力到最优的算法之旅
javascript·算法·面试
健康的猪21 分钟前
golang的cgo的一点小心得
开发语言·后端·golang
夜夜敲码43 分钟前
C语言教程(十六): C 语言字符串详解
c语言·开发语言
宋康1 小时前
C语言结构体和union内存对齐
c语言·开发语言
逢生博客1 小时前
使用 Python 项目管理工具 uv 快速创建 MCP 服务(Cherry Studio、Trae 添加 MCP 服务)
python·sqlite·uv·deepseek·trae·cherry studio·mcp服务