Created
October 4, 2021 01:43
-
-
Save jeovazero/5eec9b3a498ae5c7e2f5f3c4e0e0bbc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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