Skip to content

Instantly share code, notes, and snippets.

@karthikselva
Forked from D-side/dsu.rb
Created April 30, 2017 15:15
Show Gist options
  • Select an option

  • Save karthikselva/e510711aba51bd275a8b6ddb96f68b25 to your computer and use it in GitHub Desktop.

Select an option

Save karthikselva/e510711aba51bd275a8b6ddb96f68b25 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