- 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/
*/
classDSU {
privateint[] parentOf;
privateint[] depth;
privateintsize;
publicDSU(intsize) {
this.size = size;
this.depth = newint[size + 1];
this.parentOf = newint[size + 1];
clear(size);
}
// reset
publicvoidclear(intrange) {
this.size = range;
for (intpos = 1; pos <= range; pos++) {
depth[pos] = 0;
parentOf[pos] = pos;
}
}
// Time: O(log n), Auxiliary Space: O(1)
intgetRoot(intnode) {
introot = node;
// finding root
while (root != parentOf[root]) {
root = parentOf[root];
}
// update chain for new parent
while (node != parentOf[node]) {
intnext = parentOf[node];
parentOf[node] = root;
node = next;
}
returnroot;
}
// Time: O(log n), Auxiliary Space: O(1)
voidjoinSet(inta, intb) {
introotA = getRoot(a);
introotB = 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;
}
}
intgetNoOfTrees() {
intuniqueRoots = 0;
for (intpos = 1; pos <= size; pos++) {
if (pos == getRoot(pos)) {
uniqueRoots++;// root
}
}
returnuniqueRoots;
}
}