Problem-solving ideas
And check the template questions, use the above M erge MergeM e r g e function to achieve set merging, andfind findThe f i n d function finds the representative elements of the set, and uses whether the representative elements of the two elements are the same to judge whether they are in the same set. Both path compression and rank merging can pass this question.
Code
#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<bitset>
using namespace std;
int n,m,z,x,y,fa[10010];
int find(int x){
if(fa[x]!=x)
return fa[x]=find(fa[x]);//路径压缩
else return fa[x];
}
void merge(int x,int y){
int xx=find(x),yy=find(y);
if(xx!=yy)
fa[xx]=yy;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&z,&x,&y);
if(z==1)
merge(x,y);
if(z==2)
{
if(find(x)==find(y))
printf("Y\n");
else printf("N\n");
}
}
}