local t, n = io.read("*n", "*n") local cs = {} local vs = {} for i = 1, n do cs[i] = io.read("*n") end for i = 1, n do vs[i] = io.read("*n") end local score = {} for i = 1, t do score[i] = 0 end local mma, mfl = math.max, math.floor for i = 1, n do local c, v = cs[i], vs[i] local curc, curv = 0, 0 local csum, vsum = {}, {} while 0 < v do curc = curc + c curv = curv + v table.insert(csum, curc) table.insert(vsum, curv) v = mfl(v / 2) end for j = t, 1, -1 do for k = 1, #csum do if j + csum[k] <= t then score[j + csum[k]] = mma(score[j + csum[k]], score[j] + vsum[k]) end end end for k = 1, #csum do if csum[k] <= t then score[csum[k]] = mma(score[csum[k]], vsum[k]) end end end local ret = 0 for i = 1, t do ret = mma(ret, score[i]) end print(ret)