当前位置:网站首页>并查集模板及思想
并查集模板及思想
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;
}
边栏推荐
- 腾讯电竞的蓝翔梦
- 请问下这个hologres维表是被缓存了么?怎么直接Finished了
- 数据万象内容审核 — 共建安全互联网,专项开展“清朗”直播整治行动
- 火热的印度工厂,带不动印度制造
- 2022爱分析· 银行数字化厂商全景报告
- B站回应HR称核心用户是Loser;微博回应宕机原因;Go 1.19 正式发布|极客头条
- [redis] cache penetration and cache avalanche and cache breakdown solutions
- Excuse me this hologres dimension table is cached?How to Finished
- 企业如何选择低代码开发平台
- Looking at the ecological potential of Hongmeng OS from the evolution of MatePad Pro
猜你喜欢
随机推荐
茅台日赚1.65亿,经销商日子却越来越难
【指针初解】
精酿啤酒品牌,过把瘾就死?
How ArkUI adapter somehow the screen
【云驻共创】【HCSD大咖直播】亲授大厂面试秘诀
【LeetCode】899. 有序队列
如何避免无效的沟通
“LaMDA 存在种族歧视,谷歌的 AI 伦理不过是‘遮羞布’!”
通用型安全监测数据管理系统
【目标检测】Focal Loss for Dense Object Detection
生产环境如何删除表呢?只能在SQL脚本里执行 drop table 吗
FinClip | July 2022 Product Highlights
ICDAR比赛技术分享
【机器学习】机器学习基本概念/术语3
three.js简介
TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
PTA递归练习
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
JS 字符串转 GBK 编码超精简实现
Interviews are no longer hanged!This is the correct way to open the seven schemes of Redis distributed locks









