当前位置:网站首页>模板系列-并查集
模板系列-并查集
2022-08-02 14:10:00 【老顽固也可爱】
并查集模板
1、初始化
void init{
for(int i=1;i<=n;i++){
fa[i]=i;//把结点i的集合号初始化为其自身编号
}
}
2、查找
版本一:
int find(int i){
while(i!=pi[i]){
i=pi[i]=pi[pi[i]];
}
return pi[i];
}
版本二:
int find(int x) {
if(x != fa[x]){
//当x不等于它的爸爸时(当它是祖先时,它没有爸爸)
fa[x] = find(fa[x]);//继续找他的爸爸的爸爸
}
return fa[x];//返回祖先
}//查找
3、合并
void unity(int x, int y){
int r1 = find(x);//找到x的祖先
int r2 = find(y);//找到y的祖先
if(r1!=r2){
fa[r1] = r2;//祖先和祖先结为父子(谁是父亲谁是儿子都可以)
}
}//合并
边栏推荐
猜你喜欢
Do Windows 10 computers need antivirus software installed?
二叉树遍历之后序遍历(非递归、递归)入门详解
FP6195耐压60V电流降压3.3V5V模块供电方案
win10任务栏不合并图标如何设置
How to update Win11 sound card driver?Win11 sound card driver update method
Win11 system cannot find dll file how to fix
Win10 Settings screen out from lack of sleep?Win10 set the method that never sleep
深入理解Golang之Map
Summarize computer network super comprehensive test questions
Win11系统找不到dll文件怎么修复
随机推荐
FP7122降压恒流内置MOS耐压100V共正极阳极PWM调光方案原理图
Open the door of power and electricity "Circuit" (2): Power Calculation and Judgment
Daily - Notes
Publish module to NPM should be how to operate?Solutions to problems and mistake
Binder机制(中篇)
发布模块到npm应该怎么操作?及错误问题解决方案
Mapreduce环境详细搭建和案例实现
TCP三次握手、四次挥手
General code for pytorch model to libtorch and onnx format
Win11 keeps popping up User Account Control how to fix it
推开机电的大门《电路》(三):说说不一样的电阻与电导
镜像法求解接地导体空腔电势分布问题
用U盘怎么重装Win7系统?如何使用u盘重装系统win7?
FP7195芯片PWM转模拟调光至0.1%低亮度时恒流一致性的控制原理
Win10 computer can't read U disk?Don't recognize U disk how to solve?
STM32LL库——USART中断接收不定长信息
【我的电赛日记(一)】HMI USART串口屏
利用plot_surface命令绘制复杂曲面入门详解
Detailed explanation of RecyclerView series article directory
CMAKE