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 = Array.new(N) { 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(0, nil, @merchandises) end def dp(score, last, rest) if rest.empty? res = 0 elsif last && @memos[last][rest] res = @memos[last][rest] elsif last res = rest.map { |m| dp(@score_table[last][m].to_i, m, rest - [m]) }.max else res = rest.map { |m| dp(0, m, rest - [m]) }.max end @memos[last][rest] = res if last score + res end end puts Calc.new.run