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;
}