-
Notifications
You must be signed in to change notification settings - Fork 153
/
disjoint_set_with_undo_operation.cpp
61 lines (55 loc) · 1.43 KB
/
disjoint_set_with_undo_operation.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
/**
* Description : DisjointSet (Makes a set of sets, merge sets, set membership, no. of sets, undo last operation)
* Usage: find O(lg(N)), merge O(lg(N)), undo O(1), getComponents O(1)
* Source: https://github.com/dragonslayerx
*/
class DisjointSet {
const static int MAX = 100005;
int parent[MAX], rank[MAX];
int components;
vector<int> O;
public:
DisjointSet(int n) {
components=n;
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i]=1;
}
}
int find(int u) {
while (u != parent[u]) {
u = parent[u];
}
return u;
}
void merge(int a, int b) {
int parentA = find(a), parentB = find(b);
if (parentA == parentB) {
O.push_back(-1);
} else {
if (rank[parentA] > rank[parentB]) {
parent[parentB] = parentA;
O.push_back(parentB);
} else {
parent[parentA] = parentB;
O.push_back(parentA);
if (rank[parentA]==rank[parentB]) {
rank[parentB]++;
}
}
components--;
}
}
int getComponents() {
return components;
}
void undo() {
assert(!O.empty());
int delta = O.back();
O.pop_back();
if (delta!=-1) {
parent[delta]=delta;
components++;
}
}
};