h = {} n = gets.to_i n.times do |i| gets a, b = gets.split.map(&:to_i) tags = gets.split tags.each do |tag| if h.key?(tag) h[tag] += b else h[tag] = b end end end count = 0 h.values.uniq.sort.reverse.each do |i| ans = h.to_a.select{|a| a[1] == i} ans.transpose[0].sort.each do |tag| puts "#{tag} #{i}" count += 1 exit if count == 10 end end