-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisjoint-set-union.c++
61 lines (55 loc) · 1.13 KB
/
disjoint-set-union.c++
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
//aka union-find
//time complexity:
//Each union or find operation take O(log2(n)) time.
#include<bits/stdc++.h>
using namespace std;
const int MAX = 100000;
int arr[MAX];
int tsize[MAX];
void initialise() {
for (int i = 0; i < MAX; i++) {
arr[i] = i;
tsize[i] = 1;
}
}
int root(int i) {
while (arr[i] != i) {
arr[i] = arr[arr[i]]; //helps to flatten the graph
i = arr[i];
}
return i;
}
void uni(int a, int b) {
int roota = root(a);
int rootb = root(b);
if (tsize[a] > tsize[b]) {
arr[rootb] = roota;
tsize[roota] += tsize[rootb];
}
else {
arr[roota] = rootb;
tsize[rootb] += tsize[roota];
}
}
bool find(int a, int b) {
if (root(a) == root(b)) return true;
return false;
}
int main() {
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
initialise();
int t, a, b;
cin >> t;
while (t--) {
char c;
cin >> c >> a >> b;
if (c == 'u') {
uni(a, b);
}
else {
bool ans = find(a, b);
cout << ans;
}
}
}