当前位置:网站首页>并查集模板及思想
并查集模板及思想
2022-08-03 17:14:00 【lcy2023】
acwing相关资料:https://www.acwing.com/activity/content/problem/content/885/
基本思想
如果想合并两个集合,直接把根节点插到另一个集合的某个地方即可
路径压缩优化–时间复杂度近乎为O(1)
在问题2中,求x的集合编号与数的高度成正比,复杂度较高,所以可以进行优化,在第一次查的时候正常一步一步查到根节点while(p[x]!=x) x=p[x],但一旦找到后就会把这个线上的所有点都指向根节点,之后再查就是O(1)的复杂度
代码
模板题:https://www.acwing.com/problem/content/838/
#include <iostream>
using namespace std;
const int N = 100010;
int p[N];
int find(int x) // 返回祖宗节点+路径压缩
{
// 如果不是根节点则进行路径优化
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
//初始化
for(int i = 1; i<=n;i++) p[i]=i;
while(m--)
{
char op[2];
int a,b;
scanf("%s%d%d",op,&a,&b);
// 将根节点的父节点改为另一个集合的父节点完成合并操作
if(op[0] == 'M') p[find(a)] = find(b);
else
{
if (find(a) == find(b)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}
拓展维护集合额外信息
维护集合个数
:::info
例题:https://www.acwing.com/activity/content/problem/content/886/
:::
#include <iostream>
using namespace std;
const int N = 100010;
int p[N],cnt[N];
int find(int x)
{
if(p[x]!=x) p[x] = find(p[x]);
return p[x];
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
// 初始化
for (int i = 1; i <= n; i++)
{
p[i] = i;
cnt[i] = 1;
}
while(m--)
{
char op[5];
int a,b;
scanf("%s",op);
if(op[0]=='C')
{
scanf("%d%d",&a,&b);
a = find(a);
b=find(b);
if (a!=b){
p[a] = b;
cnt[b]+=cnt[a];
}
}else{
if (op[1] == '1')
{
scanf("%d%d",&a,&b);
if(find(a)==find(b))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}else{
scanf("%d",&a);
cout<<cnt[find(a)]<<endl;
}
}
}
return 0;
}
边栏推荐
猜你喜欢

A complete detailed tutorial on building intranet penetration ngrok (with pictures and truth)

通用型安全监测数据管理系统

掌握Redis的Sentinel哨兵原理,可助你拿到25k的offer

EasyExcel实现动态列解析和存表

JSON.stringify()的深入学习和理解

多表查询最值

Interviews are no longer hanged!This is the correct way to open the seven schemes of Redis distributed locks

一个域名对应多个IP地址

LeetCode·72.编辑距离·动态规划

J9货币论:数字经济为全球经济复苏注入力量
随机推荐
fastposter v2.9.0 程序员必备海报生成器
LeetCode·899.有序队列·最小表示法
高薪程序员&面试题精讲系列132之微服务之间如何进行通信?服务熔断是怎么回事?你熟悉Hystrix吗?
TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
FinClip | 2022 年 7 月产品大事记
Understand the recommendation system in one article: Outline 02: The link of the recommendation system, from recalling rough sorting, to fine sorting, to rearranging, and finally showing the recommend
MobileVIT实战:使用MobileVIT实现图像分类
多表查询最值
数据中台“集存通用治”功能场景说明
企业如何选择低代码开发平台
PTA递归练习
被误解的 MVC 和被神化的 MVVM(一)
完整的搭建内网穿透ngrok详细教程(有图有真相)
超分重建数据集
uniapp 去掉默认导航栏
LyScript 从文本中读写ShellCode
php之相似文章标题similar_text()函数使用
大佬们。使用flink-cdc-sqlserver 2.2.0 版本读取sqlserver2008R
【时间的比较】
组件通信--下拉菜单案例