presents = Hash.new(0) N = gets.to_i (0 ... N).each do |i| present = gets present.chop! if present[-1] == "\n" presents[present] += (i + 1) * (N - i) end presents.to_a.sort.each do |p, c| puts "#{c} #{p}" end