当前位置:网站首页>路径压缩、、
路径压缩、、
2022-08-01 23:21:00 【Wanderer001】
并查集中的find函数,可以用于查找某个节点的父亲节点,某些情况下,我们为了加快查找的速度,就要用到路径压缩的写法。
int find(int x)
{
int tmp,son;
son=x;
while(x!=pra[x])
x=pra[x];
while(son!=x)
{
tmp=pra[son];
pra[son]=x;
son=tmp;
}
return x;
}我们一开始找到了x的父亲节点,之后,我们随着(X--->X的祖先)这条路,一直把这条路上的所有节点的父节点都标记为祖先节点。从而加快了查找的速度。
################################################################
有关并查集join函数的新认识:
1.如果不考虑树的整体结构,
void join(int b1,int b2)//两颗树的合并操作
{
int x=find(b1);//找到树b1的根节点
int y=find(b2);//找到树b2的根节点
if(x!=y)//如果两棵树不同根
pra[y]=x;//链接两棵树
}2.需要考虑到树的整体结构:
void join(int b1,int b2)//两颗树的合并操作
{
int x=find(b1);//找到树b1的根节点
int y=find(b2);//找到树b2的根节点
if(x!=y)//如果两棵树不同根
pra[b2]=b1;//链接两棵树
}其他东西:
1.FIND函数能查找子节点的祖先节点
2.采用了路径压缩的FIND函数、JOIN函数可以修改子节点的父亲节点。
######################################################
路径压缩的使用前提是不考虑树的整体结构,也就是说FIND函数必须采用第一种写法。
边栏推荐
猜你喜欢
![[LeetCode304周赛] 两道关于基环树的题 6134. 找到离给定两个节点最近的节点,6135. 图中的最长环](/img/63/16de443caf28644d79dc6e6889e5dd.png)
[LeetCode304周赛] 两道关于基环树的题 6134. 找到离给定两个节点最近的节点,6135. 图中的最长环

程序员如何优雅地解决线上问题?

Access the selected node in the console

ROS2初级知识(8):Launching启动多节点

DRF generating serialization class code

6134. Find the closest node to the given two nodes - force double hundred code

leetcode刷题

仿牛客网项目第三章:开发社区核心功能(详细步骤和思路)

D - Linear Probing- 并查集

E - Integer Sequence Fair
随机推荐
Chapter 11 Working with Dates and Times
bat 之 特殊字符&转义
The monthly salary of the test post is 5-9k, how to increase the salary to 25k?
如何更好的理解的和做好工作?
Thesis understanding [RL - Exp Replay] - Experience Replay with Likelihood-free Importance Weights
Chapter 19 Tips and Traps: Common Goofs for Novices
颜色透明参数
[C language advanced] file operation (2)
域名重定向工具 —— SwitchHosts 实用教程
【C补充】链表专题 - 单向链表
excel edit a cell without double clicking
13、学习MySQL 分组
From 0 to 100: Notes on the Development of Enrollment Registration Mini Programs
excel vertical to horizontal
Oracle 数据库设置为只读及读写
请问什么是 CICD
Interpretation of the paper (GSAT) "Interpretable and Generalizable Graph Learning via Stochastic Attention Mechanism"
System availability: 3 9s, 4 9s in SRE's mouth... What is it?
E - Integer Sequence Fair
C#大型互联网平台管理框架源码:基于ASP.NET MVC+EF6+Bootstrap开发,支持多数据库