class Xxx attr_accessor :answer def initialize @answer = 0 end def set_inputs @n = gets.chomp.to_i @block_lens = gets.chomp.split(" ").map{|n| n.to_i} end def sort_proc(lens) sorting = [] keeping = [] prev = nil lens.each do |n| if prev.nil? prev = n keeping << n next end if prev > n sorting << n else keeping << n prev = n end end return [sorting, keeping] end def execute sorting, keeping = sort_proc(@block_lens) @answer = sorting.size # まだ並んでないなら再度並べる if sorting.size > 0 and keeping[0] < sorting.max sorting, buf = sort_proc(sorting.sort + keeping) @answer += sorting.size end end end if $0 == __FILE__ ins = Xxx.new ins.set_inputs ins.execute puts ins.answer end