Last active
March 31, 2025 05:22
-
-
Save caovanbi235/fa9e46e7e31ccc813c59b78a7397c926 to your computer and use it in GitHub Desktop.
Ruby UnionFind
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
class UnionFind | |
def initialize(n) | |
@d = Array.new(n, -1) | |
end | |
def root(x) | |
return x if @d[x] < 0 | |
@d[x] = root(@d[x]) | |
end | |
def is_same?(x, y) | |
root(x) == root(y) | |
end | |
def unite(x, y) | |
x = root(x) | |
y = root(y) | |
return if x == y | |
x, y = y, x if @d[x] > @d[y] | |
@d[x] += @d[y] | |
@d[y] = x | |
end | |
def size(x) | |
-@d[root(x)] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment