You are viewing a single comment's thread. Return to all comments →
Ruby implementation of Disjoint Union Set:
# https://cp-algorithms.com/data_structures/disjoint_set_union.html class DisjointSetUnion attr_reader :max def initialize @parent = {} @size = {} @max = 0 end def make_set(v) @parent[v] = v @size[v] = 1 @max = [@max, 1].max end def find(v) @parent[v] = @parent[v] == v ? v : find(@parent[v]) end def union(a, b) sa = find(a) sb = find(b) unless sa == sb sa, sb = sb, sa if @size[sa] < @size[sb] @parent[sb] = sa @size[sa] += @size[sb] @max = [@max, @size[sa]].max end end end def max_circle(queries) result = Array.new(queries.length) dsu = DisjointSetUnion.new queries.flatten.uniq.each { |n| dsu.make_set(n) } queries.each_with_index do |persons, i| dsu.union(*persons) result[i] = dsu.max end result end q = gets.to_i queries = Array.new(q) q.times do |i| queries[i] = gets.split.map(&:to_i) end puts max_circle(queries)
Seems like cookies are disabled on this browser, please enable them to open this website
Friend Circle Queries
You are viewing a single comment's thread. Return to all comments →
Ruby implementation of Disjoint Union Set: