A=$<.map{|s|s.split.map &:to_i} N=A.shift[0] V=A.pop[0] B,C=A.transpose d=[] N.times{|i|C.sum.downto(C[i]){|j|d[j]=[d[j]||0,B[i]+d[j-C[i]]||=0].max}} p [1,a=d.index(V)].max b=d.rindex V puts a