SHENTONG_ZY @ 2021-09-27 13:16:33
#include<bits/stdc++.h>
using namespace std;
int a[100000],n,m,x,y,z;
int da(int x){
if(a[x]==x) return x;
else return da(a[x]);
}
bool check(int x,int y){
if(da(x)==da(y)) return true;
return false;
}
int hb(int x,int y){
if(check(x,y)==false){
a[da(x)]=da(y);
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++) a[i]=i;
for(int i=1;i<=m;i++){
scanf("%d%d%d",&z,&x,&y);
if(z==1) hb(x,y);
else{
if(check(x,y)==true) printf("Y\n");
else printf("N\n");
}
}
return 0;
}
by KazamiHina @ 2021-09-27 13:18:29
路径压缩
by SHENTONG_ZY @ 2021-09-27 13:21:08
@High_Score 谢谢
by qwq自动机 @ 2021-09-27 13:22:13
@杨NB da
函数中要用路径压缩。不然会被一条链卡掉
一般这样写
int da(int x)
{
if (a[x] == x) return x;
a[x] = da(a[x]);
return a[x];
}