并查集实现(路径压缩)

并查集 Union Find 算法

定义

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

基本操作

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

具体实现

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

初始化:

每一个点都是一个集合,因此自己的父节点就是自己father_dicti=i,size_dicti=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
相关推荐
Flynt3 分钟前
Astra 自主跑了 35 小时烧掉 40 亿 token,产出为零:我给 Agent 加了三道闸
python·aigc·agent
mldong6 分钟前
Python 开发者也有自己的轻量工作流引擎了:pip install 一行,5 分钟跑通一条审批流
后端·python·架构
郑州光合科技余经理12 分钟前
本地生活系统:多业务订单字段怎么分账本导出
java·开发语言·前端·数据库·uni-app·php·ai编程
weixin199701080161 小时前
《跨境二手ERP的3种对接模式:自研API / SaaS中间件 / 平台认证服务商,怎么选?》(附Python源码)
开发语言·python·中间件
B2_Proxy1 小时前
Python 爬虫代理中间件开发:统一处理 403、429 与自动重试机制
python
学代码的CJY1 小时前
Python序列类型详解
python
529宝宝起名网1 小时前
用 Python 爬取古籍文献中的名字用例数据库:从二十四史到诗词文集的历史名字采集与分析
python
传奇开心果编程3 小时前
【Rust入门知识点学与练】第24课:Trait 基础
开发语言·学习·rust
GreenTea7 小时前
vLLM 与 SGLang KV Cache 底层实现机制深度调研报告
前端·后端·算法
Bode_20028 小时前
多资源规划(含生产调度、库存管理及产能规划)的创新优化算法
算法·调度