forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DisjointSet.kt
44 lines (37 loc) Β· 963 Bytes
/
DisjointSet.kt
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
package algo.datastructures
class DisjointSet(val size: Int) {
private val parent = IntArray(size)
private val rank = ByteArray(size)
public var count = size
private set
init {
for (i in parent.indices) {
parent[i] = i
}
}
public fun connected(v: Int, w: Int): Boolean {
return find(v) == find(w)
}
public fun find(v: Int): Int {
var v = v
while (parent[v] != v) {
parent[v] = parent[parent[v]]
v = parent[v]
}
return v
}
public fun union(v: Int, w: Int) {
val rootV = find(v)
val rootW = find(w)
if (rootV == rootW) return
if (rank[rootV] > rank[rootW]) {
parent[rootW] = rootV
} else if (rank[rootW] > rank[rootV]) {
parent[rootV] = rootW
} else {
parent[rootV] = rootW
rank[rootW]++
}
count--
}
}