博客
关于我
并查集(初学)
阅读量: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/

你可能感兴趣的文章
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm install的--save和--save-dev使用说明
查看>>
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>
npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
查看>>
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>
npm scripts 使用指南
查看>>
npm should be run outside of the node repl, in your normal shell
查看>>