P3367 【模板】并查集
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> using namespace std; int n,m,zi,xi,yi; int father[10001]; int find(int x) //寻找根结点并压缩路径 { if(father[x]!=x) father[x]=find(father[x]); return father[x]; } void unionn(int x,int y) //合并两个集合 { x=find(x); y=find(y); father[y]=x; } bool judge(int x,int y) //判断元素是否属于同一集合 { x=find(x); y=find(y); if(x==y) return true; else return false; } int caozuo(int z,int x,int y) { if(z==1) unionn(x,y); if(z==2) { if(judge(x,y)) printf("Y\n"); else printf("N\n"); } } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) //初始化 father[i]=i;for(int i=1;i<=m;i++) { scanf("%d%d%d",&zi,&xi,&yi); caozuo(zi,xi,yi); } return 0; }
原文地址:https://www.cnblogs.com/xiaoyezi-wink/p/10758162.html
时间: 2024-11-05 13:47:22