随笔 - 297  文章 - 0 评论 - 0 阅读 - 4873
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

今天学习了并查集的知识,一般用于合并鞍和查询元素是否在集合里

模板

int p[x];//p[x]是x的祖宗节点
int find(int x)//find函数是用来找祖宗节点的(运用了路径压缩:将每个节点都指向根节点)
{
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}

例题

#include<iostream>
using namespace std;
const int N=1e5+10;
int n,m;
int p[N];
int find(int x)
{
if(p[x]!=x) p[x]=find[p[x]];//路径压缩,将每个节点都指向根节点
reuturn p[x]
}
int main()
{
cin>>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;
}
}
}
posted on   许七安gyg  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示