class ListNumber attr_reader :list def initialize(n) @n = n @list = {} ((@n**(@n-2))..(@n**@n - 1)).each do |ls| flag = true @n.times do |i| unless num_index(ls, i) flag = false break end end if flag @list[ls] = 0 end end end def num_index(ls, x) a = ls @n.times do |i| if x == a % @n return i else a = a / @n end end return nil end def match(ls, l, g) a = ls @n.times do |i| check = a % @n if check == l return true elsif check == g return false end a = a / @n end raise "ilegal #{ls.to_s(@n)}, #{l}, #{g}" end def add_score(l, g, s) @list.each do |ls, score| if match(ls, l, g) @list[ls] = score + s end end end def max_score @list.values.max end end n, m = gets.split.map(&:to_i) list = [] m.times do list << gets.split.map(&:to_i) end lsnum = ListNumber.new(n) list.each do |ss| lsnum.add_score(ss[0], ss[1], ss[2]) end puts lsnum.max_score