-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathDSU.java
executable file
·68 lines (63 loc) · 1.81 KB
/
DSU.java
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
/*
* Author : joney_000[developer.jaswant@gmail.com]
* Algorithm : Disjoint Set Union O(log n) + path optimization
* Platform : Codeforces/Leetcode. eg. problem: https://leetcode.com/problems/satisfiability-of-equality-equations/
*/
class DSU {
private int[] parentOf;
private int[] depth;
private int size;
public DSU(int size) {
this.size = size;
this.depth = new int[size + 1];
this.parentOf = new int[size + 1];
clear(size);
}
// reset
public void clear(int range) {
this.size = range;
for (int pos = 1; pos <= range; pos++) {
depth[pos] = 0;
parentOf[pos] = pos;
}
}
// Time: O(log n), Auxiliary Space: O(1)
int getRoot(int node) {
int root = node;
// finding root
while (root != parentOf[root]) {
root = parentOf[root];
}
// update chain for new parent
while (node != parentOf[node]) {
int next = parentOf[node];
parentOf[node] = root;
node = next;
}
return root;
}
// Time: O(log n), Auxiliary Space: O(1)
void joinSet(int a, int b) {
int rootA = getRoot(a);
int rootB = getRoot(b);
if (rootA == rootB) {
return;
}
if (depth[rootA] >= depth[rootB]) {
depth[rootA] = Math.max(depth[rootA], 1 + depth[rootB]);
parentOf[rootB] = rootA;
} else {
depth[rootB] = Math.max(depth[rootB], 1 + depth[rootA]);
parentOf[rootA] = rootB;
}
}
int getNoOfTrees() {
int uniqueRoots = 0;
for (int pos = 1; pos <= size; pos++) {
if (pos == getRoot(pos)) {
uniqueRoots++;// root
}
}
return uniqueRoots;
}
}