首页 > 其他分享 >合并集合

合并集合

时间:2023-03-11 13:11:37浏览次数:29  
标签:int px 合并 节点 集合 find

 

 

 合并集合:1.将两个集合合并2.询问两个集合是否在一个集合中

如何求树根的编号:往上走

如何合并两个集合:px是x的集合编号,py是y的集合编号,合并直接px=y。(给px找了个爸爸,爸爸是y)(让x的祖宗节点的父亲等于y的祖宗节点)

 

 

 #include<iostream>

const int N=1e5+10;

int p[N];

 

using namespace std;

int find(int x){//找到x的祖宗节点

if(p[x]!=x){//如果x不是根节点

p[x]=find(p[x]);//就让父节点等于祖宗节点

return p[x];//返回父节点

}

int main(){

int n,m;

cin>>n>>m;

for(int i=1;i<=n;i++){

p[i]=i;//初始的时候,每个元素自己就是一个集合

}

while(m--){

char op[2];

int a,b;

cin>>op>>a>>b;

if(op=='M'){

p[find(a)]=find(b);

}else {

if(find(a)==find(b)) cout<<"Yes"<<endl;

else cout<<"No"<<endl;

}

}

return 0;

}

 

标签:int,px,合并,节点,集合,find
From: https://www.cnblogs.com/chenxinyue/p/17201462.html

相关文章