N = gets.to_i scores = Hash.new(0) N.times do no = gets.to_i m, s = gets.split.map(&:to_i) tags = gets.chomp.split tags.each do |tag| scores[tag] += s end end scores.sort_by { |name, score| [-score, name] }.take(10).each do |name, score| puts [name, score].join(' ') end