-
Notifications
You must be signed in to change notification settings - Fork 0
/
DSU.cpp
81 lines (71 loc) · 1.38 KB
/
DSU.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <bits/stdc++.h>
using namespace std;
// Disjoint Set Union, O(alpha(n))
struct DSU {
int c;
vector<int> par, sz;
DSU() {}
DSU(int n) {
init(n);
}
void init(int n) {
c = n;
par.resize(n);
iota(par.begin(), par.end(), 0);
sz.assign(n, 1);
}
int find(int a) {
return (par[a] == a ? a : (par[a] = find(par[a])));
}
bool same(int a, int b) {
return find(a) == find(b);
}
void merge(int a, int b) {
if ((a = find(a)) == (b = find(b))) {
return;
}
if (sz[a] > sz[b]) {
swap(a, b);
}
par[a] = b;
sz[b] += sz[a];
c--;
}
int size(int a) {
return sz[find(a)];
}
int count() {
return c;
}
};
void solve() {
int n, q;
cin >> n >> q;
DSU dsu(n);
while (q--) {
int op;
cin >> op;
if (op == 1) {
int a, b;
cin >> a >> b;
a--, b--;
dsu.merge(a, b);
}
else if (op == 2) {
int a, b;
cin >> a >> b;
a--, b--;
cout << (dsu.same(a, b) ? "YES\n" : "NO\n");
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}