import std.algorithm, std.array, std.container, std.range, std.bitmanip; import std.numeric, std.math, std.bigint, std.random, core.bitop; import std.string, std.conv, std.stdio, std.typecons; void main() { auto t = readln.chomp.to!int; auto n = readln.chomp.to!int; auto ci = readln.split.map!(to!int).array; auto vi = readln.split.map!(to!int).array; auto memo = new int[](t + 1); memo[0] = 0; memo[1..$] = -1; foreach (i; 0..n) { auto memo2 = new int[](t + 1); memo2[] = -1; auto dvi = calcDvi(vi[i]); foreach (j; ci[i]..t + 1) { if (memo[j - ci[i]] >= 0) { foreach (k, dv; dvi) { auto m = j + k * ci[i]; if (m <= t) { if (memo2[m] >= 0) memo2[m] = max(memo[j - ci[i]], dv); else memo2[m] = memo[j - ci[i]] + dv; } } } } foreach (j; 0..t + 1) { if (memo2[j] >= 0) { if (memo[j] >= 0) memo[j] = max(memo[j], memo2[j]); else memo[j] = memo2[j]; } } } writeln(memo.reduce!(max)); } int[] calcDvi(int v) { int[] dvi; for (auto c = v; v > 0; v /= 2, c+= v) dvi ~= c; return dvi; }