-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathMergingCommunities.kt
49 lines (41 loc) · 1.12 KB
/
MergingCommunities.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
45
46
47
48
49
class UnionFind(size: Int) {
private val parent = IntArray(size) { it }
private val size = IntArray(size) { 1 }
// With comment
fun union(x: Int, y: Int) {
val repX = find(x)
val repY = find(y)
if (repX != repY) {
// If 'repX' represents a larger community, connect
// 'repY 's community to it.
if (size[repX] > size[repY]) {
parent[repY] = repX
size[repX] += size[repY]
} else {
// Otherwise, connect 'repX's community to 'repY'.
parent[repX] = repY
size[repY] += size[repX]
}
}
}
fun find(x: Int): Int {
if (x == parent[x]) {
return x
}
// Path compression.
parent[x] = find(parent[x])
return parent[x]
}
fun getSize(x: Int): Int {
return size[find(x)]
}
}
class MergingCommunities(n: Int) {
private val uf = UnionFind(n)
fun connect(x: Int, y: Int) {
uf.union(x, y)
}
fun getCommunitySize(x: Int): Int {
return uf.getSize(x)
}
}