T = gets.to_i N = gets.to_i C = gets.split.take(N).map(&:to_i) V = gets.split.take(N).map(&:to_i) CV = C.zip(V).sort_by{|c, v|}.flat_map{|c,v| a = [] while v > 0 a << [c,v] v /= 2 end a } $dp = {} def f(t, i) $dp[[t,i]] ||= if t == 0 || i >= CV.size 0 elsif t < CV[i][0] f(t, i + 1) else [f(t, i + 1), CV[i][1] + f(t - CV[i][0], i+1)].max end end p f(T, 0)