P3367 【模板】并查集
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 1e4+5; 4 int pa[maxn], n, m; 5 void init() { 6 for (int i = 1; i <= n; i++) pa[i] = i; 7 } 8 int findset(int x) { 9 return pa[x] != x ? pa[x] = findset(pa[x]) : x; 10 } 11 void merge(int x, int y) { 12 int fx = findset(x); 13 int fy = findset(y); 14 if (fx == fy) return; 15 pa[fx] = fy; 16 } 17 int main() { 18 scanf("%d%d",&n,&m); 19 init(); 20 while (m--) { 21 int z, x, y; scanf("%d%d%d",&z,&x,&y); 22 if (z == 1) merge(x,y); 23 else { 24 if (findset(x) == findset(y)) puts("Y"); 25 else puts("N"); 26 } 27 } 28 return 0; 29 }