并查集实现(路径压缩)

并查集 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
相关推荐
嫩萝卜头儿5 分钟前
2 - 复杂度收尾 + 链表经典OJ
数据结构·算法·链表·复杂度
c++之路14 分钟前
C++20概述
java·开发语言·c++20
星马梦缘18 分钟前
算法设计与分析 作业二 答案与解析
算法·图论·dfs·bfs·floyd-warshall·bellman_ford·多源最短路
玛丽莲茼蒿18 分钟前
Leetcode hot100 每日温度【中等】
算法·leetcode·职场和发展
cjp56026 分钟前
009.UG二次开发,任务环境草图优化3(高级功能生成直线)
算法
芝士就是力量啊 ೄ೨29 分钟前
Python如何编写一个简单的类
开发语言·python
样例过了就是过了38 分钟前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
胖虎喜欢静香38 分钟前
从零到一快速实现 Mini DeepResearch
人工智能·python·开源
逻辑驱动的ken40 分钟前
Java高频面试考点18
java·开发语言·数据库·算法·面试·职场和发展·哈希算法
MoonBit月兔40 分钟前
「Why MoonBit 」第一期——Singularity Note AI 学习助手
开发语言·人工智能·moonbit