def scoring(seq) hash = {}.tap do |h| seq.each_with_index do |elem, index| h[elem] = index end end I.sum do |l, r, s| hash[l] < hash[r] ? s : 0 end end N, M = gets.split.map(&:to_i) I = (1..M).map { gets.split.map(&:to_i) } puts Array.new(N) { |index| index }.permutation.map { |seq| scoring(seq) }.max