题目链接:并查集模板
上代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m,fa[1000001];
int father(int x)
{
if(fa[x]==x) return x;
else return father(fa[x]);
}
void hb(int x,int y)//有时候可以省略
{
int fx=father(x),fy=father(y);
if(fx<fy) fa[fy]=fx;
else fa[fx]=fy;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
fa[i]=i;
}
for(int i=1;i<=m;i++)
{
int t,x,y;
cin>>t>>x>>y;
if(t==1) hb(x,y);
else if(t==2)
{
if(father(x)==father(y))
{
cout<<'Y'<<endl;
}
else
{
cout<<'N'<<endl;
}
}
}
return 0;
}