Skip to content

Instantly share code, notes, and snippets.

@D-side
Created July 9, 2014 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save D-side/e8a521148105d794b07e to your computer and use it in GitHub Desktop.
Save D-side/e8a521148105d794b07e to your computer and use it in GitHub Desktop.
Primitive Ruby Disjoint-Set
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