并查集模板

Luogu P3367

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 const int MAXN = 2e5;
 6 
 7 int fa[MAXN];
 8 
 9 int find(int x) {
10     return fa[x] == x ? fa[x] : (fa[x] = find(fa[x]));
11 }
12 
13 void merge(int x, int y) {
14     fa[find(y)] = find(x);
15 }
16 
17 int main() {
18     ios::sync_with_stdio(false);
19     int n, m, opt, x, y;
20     cin >> n >> m;
21     for(int i = 0; i < n; i++)
22         fa[i] = i;
23     while(m--) {
24         cin >> opt >> x >> y;
25         if(opt == 2) {
26             cout << (find(x) == find(y) ? "Y" : "N") << endl;
27         } else {
28             merge(x, y);
29         }
30     }
31     return 0;
32 }
View Code

 

posted @ 2018-08-22 11:40  zhylj  阅读(146)  评论(0编辑  收藏  举报