Last active
March 15, 2020 05:16
-
-
Save joanromano/d22e976f101967eb5d66 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
struct HeightedUnion { | |
typealias QuickUnionRootHeight = (root: Int, height: Int) | |
private var ids: [Int] | |
// Complexity: O(n) | |
init(_ N: Int) { | |
ids = Array(0..<N) | |
} | |
private func rootHeight(var i: Int) -> QuickUnionRootHeight { | |
var height = 1 | |
while (i != ids[i]) { | |
i = ids[i] | |
height++ | |
} | |
return (i, height) | |
} | |
// Complexity: O(n) - Worst carse we will traverse everything | |
func connected(p: Int, q: Int) -> Bool { | |
return rootHeight(p).root == rootHeight(q).root | |
} | |
// Complexity: O(n) - Worst carse we will traverse everything | |
mutating func union(from: Int, _ to: Int) { | |
let rootHeightFrom = rootHeight(from) | |
let rootHeightTo = rootHeight(to) | |
if rootHeightFrom.height <= rootHeightTo.height { | |
ids[from] = to | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment