并查集

1,合并集合(并查集)

//并查集
#include<iostream>
using namespace std;
const int N=100010;

int n,m;
int p[N]; // 存每个元素的根节点是谁
// 返回 x 的祖宗节点
int find(int x)
{
	if(p[x]!=x) p[x]=find(p[x]);
	return p[x];
}

int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	
	cin>>n>>m;
	// 初试的时候每个元素都是一个单独的集合,p 值都是自己
	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;
}

2,并查集 (查找某个点所在集合的点的个数)

#include<iostream>
using namespace std;
const int N=100010;
int n,m;
int p[N],size[N];

int find(int x)
{
	if(p[x]!=x) p[x]=find(p[x]);
	return p[x];
}

int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		p[i]=i;
		size[i]=1;
	}
	while(m--)
	{
		char op[5];
		int a,b;
		cin>>op;
		// C 在 a b 之间连一条边
		if(op[0]=='C')
		{
			cin>>a>>b;
			if(find(a)==find(b)) continue;
			size[find(b)]+=size[find(a)];
			p[find(a)]=find(b);
		}
		// 询问 a点 b点是否在同一个连通块中
		else if(op[1]=='1')
		{
			cin>>a>>b;
			if(find(a)==find(b)) puts("Yes");
			else puts("No");
		}
		// 询问 a 所在的连通块中点的数量
		else
		{
			cin>>a;
			cout<<size[find(a)]<<endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值