我用pre[]数组维护前驱,find函数用于找前驱,那为什么check函数中不能用pre[a]==pre[b]来判断a,b前驱是否一致呢
AC Code
#include<bits/stdc++.h>
using namespace std;
const int N = 200005;
int n,m,pre[N],z,x,y;
int find(int x){
if(pre[x]==x) return x;
return pre[x]=find(pre[x]);
}
void Merge(int x,int y){
int fx=find(x);
int fy=find(y);
if(fx!=fy)
pre[fx]=fy;
return;
}
bool check(int a,int b){
if(find(a)==find(b)) return true;
return false;
}
int main(){
cin>>n>>m;
for(int i=1;i<=m;i++)
pre[i]=i;
while(m--){
cin>>z>>x>>y;
if(z==1)
Merge(x,y);
else if(z==2)
cout<<(check(x,y)?"Y":"N")<<endl;
}
return 0;
}