并查集模版
2025-07-12 19:56:29
发布于:浙江
#include<bits/stdc++.h>
using namespace std;
int n,m,fa[200005];
int f(int x){
return fa[x]==x?x:fa[x]=f(fa[x]); //寻找父亲节点
}
void u(int x,int y){
if(f(x)==f(y))return;//合并两个集合
fa[f(x)]=f(y);
}
int main(){
cin >> n >> m;
for(int i=1;i<=n;i++)fa[i]=i;//初始化fa数组
while(m--){
int x,y,z;
cin >> z >> x >> y;
if(z==1)u(x,y);//合并操作
else if(f(x)==f(y))cout << "Y\n";//判断是否在同一集合
else cout << "N\n";
}
return 0;
}
这里空空如也








有帮助,赞一个