class PriorityQueue attr_reader :elements def initialize @elements = [nil] end def <<(element) @elements << element bubble_up(@elements.size - 1) end def pop exchange(1, @elements.size - 1) max = @elements.pop bubble_down(1) max end def size @elements.size-1 end def head @elements[1] end private def bubble_up(index) parent_index = (index / 2) return if index <= 1 return if @elements[parent_index] >= @elements[index] exchange(index, parent_index) bubble_up(parent_index) end def bubble_down(index) child_index = (index * 2) return if child_index > @elements.size - 1 not_the_last_element = child_index < @elements.size - 1 left_element = @elements[child_index] right_element = @elements[child_index + 1] child_index += 1 if not_the_last_element && right_element > left_element return if @elements[index] >= @elements[child_index] exchange(index, child_index) bubble_down(child_index) end def exchange(source, target) @elements[source], @elements[target] = @elements[target], @elements[source] end end l = PriorityQueue.new r = PriorityQueue.new Q, K = gets.split.map &:to_i $<.map{|s| if s[/^1 /] v = $'.to_i if l.size < K l << v elsif v < l.head r << -l.pop l << v else r << -v end else if l.size < K p -1 else p l.pop l << -r.pop if r.size > 0 end end }