Luogu P3367 【模板】并查集
#include<cstdio> using namespace std; int fa[10005]; int n,m,x,y,z,xx,yy; int getfather(int x){ if(x == fa[x])return x; return fa[x] = getfather(fa[x]); //这儿也可以写成“fa[x] = getfather(fa[x]);return fa[x];” } int main(){ scanf("%d%d",&n,&m); for(int i = 1;i <= n;i++) fa[i] = i; while(m){ m--; scanf("%d%d%d",&z,&x,&y); xx = getfather(x); yy = getfather(y); if(z == 1) //合并 fa[xx] = yy; if(z == 2) //查询 if(xx == yy)printf("Y\n"); else printf("N\n"); } return 0; }