将一个集合的元素都指向一个根节点
例题在这→https://www.luogu.org/problem/P3367
#include<bits/stdc++.h>using namespace std;
const int MAX=200010;
int f[MAX];
int find(int x);
void fun(int x,int y)
{
f[find(f[x])]=find(y); //找到x的根节点和y的根节点,并使x的根节点指向y的根节点
}
int find(int x)
{
if(f[x]==x)
return x;
return f[x]=find(f[x]); //返回x指向的根节点的根节点,并使x指向最终的根节点
}
int main()
{
int N,M;
scanf("%d%d",&N,&M);
for(int i=1;i<=N;i++)
f=i;
while(M--)
{
int Z,X,Y;
scanf("%d%d%d",&Z,&X,&Y);
if(Z==1)
fun(X,Y);
else
if(find(X)==find(Y))
cout<<"Y"<<endl;
else
cout<<"N"<<endl;
}
return 0;
}