#include #include using std::vector; int optimal_weight(int W, const vector &w) { int I = w.size(); int *m = new int[(W + 1) * (I + 1)]; int *current = &m[W + 2]; int *not_taken = &m[1]; // each item for (int i = 1; i <= I; i++) { int wi = w[i - 1]; for (int k = 1; k <= W; k++) { if (k >= wi) { int taken = *(not_taken - wi) + wi; *current = ((taken > *not_taken) ? taken : *not_taken); } else *current = *not_taken; current++; not_taken++; } // skip first column current++; not_taken++; } /* for (int i = 0; i <= I; i++) { */ /* for (int k = 0; k <= W; k++) */ /* std::cout << m[(W +1) * i + k] << " "; */ /* std::cout << std::endl; */ /* } */ int ret = *(current - 2); delete [] m; return ret; } int main() { int n, W; std::cin >> W >> n; vector w(n); for (int i = 0; i < n; i++) { std::cin >> w[i]; } std::cout << optimal_weight(W, w) << '\n'; }