当前位置:网站首页>并查集模板及思想
并查集模板及思想
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;
}
边栏推荐
- ICDAR比赛技术分享
- A complete detailed tutorial on building intranet penetration ngrok (with pictures and truth)
- 数字资产的价值激发:NFT 质押
- PMP试题 | 每日一练,快速提分
- 酷开科技 × StarRocks:统一 OLAP 分析引擎,全面打造数字化的 OTT 模式
- 【数据库数据恢复】SqlServer数据库无法读取的数据恢复案例
- 火热的印度工厂,带不动印度制造
- 面试突击:什么是粘包和半包?怎么解决?
- 5. Longest Palindromic Substring
- TiKV & TiFlash accelerate complex business queries丨TiFlash application practice
猜你喜欢
随机推荐
请问下这个hologres维表是被缓存了么?怎么直接Finished了
LeetCode·899.有序队列·最小表示法
J9货币论:数字经济为全球经济复苏注入力量
面试突击:什么是粘包和半包?怎么解决?
沃尔沃:这是会“种草”的“安全感”!
组件通信--下拉菜单案例
超分重建数据集
我想请问下,我们的数据库是在亚马逊,Dataworks 连不通,怎么办?
【指针初解】
产品-Axure9英文版,轮播图效果
组件通信-父传子组件通信
uniapp 切换 history 路由模
node连接mongoose数据库流程
【目标检测】Focal Loss for Dense Object Detection
酷开科技 × StarRocks:统一 OLAP 分析引擎,全面打造数字化的 OTT 模式
TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
国内首发可视化智能调优平台,小龙带你玩转KeenTune UI
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
FinClip | 2022 年 7 月产品大事记
【Metaverse系列一】元宇宙的奥秘




![[Unity Getting Started Plan] Basic Concepts (7) - Input Manager & Input Class](/img/a7/950ddc6c9eeaa56fe0c3165d22a7d2.png)




