require "set" N = gets.to_i $chemistory = {} N.times.each{|y| gets.split.take(N).map(&:to_i).each_with_index{|v, x| $chemistory[[x,y]] = v } } $dp={} def g(unused) $dp[unused] ||= if unused.empty? 0 else a = unused.first r = 0 (unused - [a]).each{|b| r = [r, $chemistory[[a,b]] + g(unused - [a, b])].max } r end end p g(Set.new(0...N))