合并集合(模板题)

合并集合

![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210518193014218.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MzAzNzM3OQ==,size_16,color_FFFFFF,t_70)

输入样例:

4 5
M 1 2
M 3 4
Q 1 2
Q 1 3
Q 3 4

输出样例:

Yes
No
Yes

模板:

//并查集
//1.讲两个集合合并 2.询问两个元素是否再一个集合当中 
// 如何判断树根
// 如何求x的集合编号
// 如何合并两个集合 px是x的集合编号 py是y的集合编号 。 
#include<iostream>
using namespace std;
const int N = 100010;
int n,m;
int p[N];
int find(int x){ //返回 x 的祖宗结点 + 路径压缩  
	if(p[x]!=x) p[x]=find(p[x]);
	return p[x];
}
int main(){
	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)) puts("Yes");
			else puts("No");
		}
	}
	return 0;
}


 

posted @ 2022-03-22 14:58  panse·  阅读(20)  评论(0)    收藏  举报