Created
July 9, 2014 07:36
-
-
Save D-side/e8a521148105d794b07e to your computer and use it in GitHub Desktop.
Primitive Ruby Disjoint-Set
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 DSU | |
def initialize(x) | |
@array = Array.new(x) {|i| i } | |
end | |
def find(x) | |
return x if @array[x] == x | |
@array[x] = find(@array[x]) | |
end | |
def union(a, b) | |
@array[find(a)] = @array[find(b)] | |
end | |
def sets | |
@array.collect{ |i| find(i) }.uniq.length | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment