博客
关于我
并查集(初学)
阅读量:334 次
发布时间:2019-03-04

本文共 846 字,大约阅读时间需要 2 分钟。

并查集是一种高效的数据结构管理算法,主要用于合并和查找操作。它通过路径压缩和按秩合并两个优化手段,确保了几乎常数时间复杂度的性能。

并查集的基本原理

并查集由两个主要函数组成:查找(Find)和合并(Union)。查找函数用于确定节点所属的集合,合并函数用于将两个集合合并成一个。

查找函数(Find)

查找函数的主要作用是找到一个节点的根节点,通过路径压缩优化,将节点直接连接到根节点,减少后续查询的时间。

int find(int root) {    int son = root;    while (root != pre[root]) { // 查找上级        root = pre[root];    }    return root; // 返回上级}

合并函数(Union)

合并函数用于将两个节点所在的集合合并。首先查找两个节点的根节点,如果根节点不同,则将其中一个根节点的父节点指向另一个根节点。

int union(int start, int finish) {    int root1 = find(start);    int root2 = find(finish);    if (root1 != root2) { // 如果父类节点不相同(既构成不了环路)        pre[root1] = root2;    }}

路径压缩优化

为了提升查找效率,查找函数会在路径压缩过程中将节点直接连接到根节点,减少后续查找的时间。

while (son != root) { // 路径压缩    int cmp = pre[son];    pre[son] = root; // 把上级节点赋值为根节点    son = cmp;}

按秩合并优化

在合并两个集合时,按秩合并优化会将较小的树合并到较大的树上,保持树的高度平衡,确保操作的时间复杂度。

通过以上方法,并查集能够高效地管理图中的连通区域,广泛应用于图论、网络管理和分布式系统等领域。

转载地址:http://xxqq.baihongyu.com/

你可能感兴趣的文章
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>