-
Notifications
You must be signed in to change notification settings - Fork 0
/
disjoint_set.h
51 lines (45 loc) · 1.04 KB
/
disjoint_set.h
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
#ifndef DISJOINT_SET_H
#define DISJOINT_SET_H
class DisjointSet {
private:
int* parent;
int* rank;
int size;
public:
DisjointSet(int n) {
size = n;
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
~DisjointSet() {
delete[] parent;
delete[] rank;
}
int findSet(int x) {
if (parent[x] != x) {
parent[x] = findSet(parent[x]);
}
return parent[x];
}
void unionSets(int x, int y) {
int rootX = findSet(x);
int rootY = findSet(y);
if (rootX != rootY) {
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
}
else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
}
else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
};
#endif