# frozen_string_literal: true Image = Struct.new(:num, :score, :tags) N = gets.to_i IMAGES = N.times.map do n = gets.to_i _m, s = gets.chomp.split.map(&:to_i) tags = gets.chomp.split Image.new(n, s, tags) end tags = {} IMAGES.each do |image| image.tags.each do |tag| tags[tag] ||= 0 tags[tag] += image.score end end tags = tags.to_a ORDERED = tags.sort { |a, b| a[1] == b[1] ? a[0] <=> b[0] : b[1] <=> a[1] } .compact.map { |tag, score| "#{tag} #{score}" } RESULT = ORDERED[0, [10, ORDERED.size].min].join("\n") puts RESULT