inputs = STDIN.readlines.map(&:chomp) N, M = inputs[0].split(/\s+/).map(&:to_i) SCORES = inputs[1..-1].map { |line| line.split(/\s+/).map(&:to_i) } class Calc def initialize @memos = Hash.new @merchandises = (0...N).to_a @score_table = Hash.new { |h, k| h[k] = Hash.new } SCORES.each do |t| @score_table[t[0]][t[1]] = t[2] end end def run dp([]) end def dp(used) if (@merchandises - used).empty? res = 0 elsif @memos[used] res = @memos[used] else res = (@merchandises - used).map { |m| used.map { |u| @score_table[u][m].to_i }.inject(:+).to_i + dp((used + [m]).sort) }.max end @memos[used] = res res end end puts Calc.new.run