N, Q = gets.split.map(&:to_i) Component = Struct.new(:id, :vertices, :next, :prev) @component_of = Array.new(N) { |i| Component.new(i, [i], nil) } N.times do |i| @component_of[i].next = @component_of[(i + 1) % N] @component_of[i].prev = @component_of[(i - 1) % N] end def merge(u, v) x, y = @component_of[u], @component_of[v] return false if x.id == y.id x, y = y, x if x.vertices.size < y.vertices.size # merge y to x y.vertices.each do |v| x.vertices << v @component_of[v] = x end # delete y y.next.prev, y.prev.next = y.prev, y.next true end Q.times do t, *q = gets.split.map(&:to_i) case t when 1 merge(q[0] - 1, q[1] - 1) when 2 x = @component_of[q[0] - 1] if x.next.id == x.id puts -1 else puts x.next.vertices[0] + 1 end end end