Skip to content

Instantly share code, notes, and snippets.

@jeovazero
Created October 4, 2021 01:43
Show Gist options
  • Save jeovazero/5eec9b3a498ae5c7e2f5f3c4e0e0bbc3 to your computer and use it in GitHub Desktop.
Save jeovazero/5eec9b3a498ae5c7e2f5f3c4e0e0bbc3 to your computer and use it in GitHub Desktop.
/* author: jeovazero */
/**
* Linking by size + Path halving
*/
class UnionFind(size: Int) {
val roots = IntArray(size)
val sizes = IntArray(size)
var rootsSize = size - 1
init {
for(i in 0..(size - 1)) {
roots[i] = i
sizes[i] = 0
}
}
fun find(node: Int): Int {
var i = node
while(roots[i] != i) {
roots[i] = roots[roots[i]]
i = roots[i]
}
return i
}
fun union(a: Int, b: Int) {
val fa = find(a)
val fb = find(b)
if (fa == fb) return
if (sizes[fa] < sizes[fb]) {
roots[fa] = fb
sizes[fb] += sizes[fa]
} else {
roots[fb] = fa
sizes[fa] += sizes[fb]
}
rootsSize--
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment