Luogu P3367 【模板】並查集
阿新 • • 發佈:2018-11-03
#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; }