Skip to content

Instantly share code, notes, and snippets.

@bruceoutdoors
Last active December 13, 2015 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bruceoutdoors/615c7267a5cd8dcae5f7 to your computer and use it in GitHub Desktop.
Save bruceoutdoors/615c7267a5cd8dcae5f7 to your computer and use it in GitHub Desktop.
Dynamic programming solution to http://www.spoj.com/problems/KNAPSACK/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v, c;
int S, N; cin >> S >> N;
// sloted for easy array access; values won't be used.
c.push_back(-1);
v.push_back(-1);
int ct, vt;
for (int i = 0; i < N; i++) {
cin >> ct >> vt;
c.push_back(ct);
v.push_back(vt);
}
vector< vector<int> > DP(N + 1, vector<int>(S + 1, 0));
for (int i = 1; i <= N; i++) { // i is scope of items in consideration
for (int w = 1; w <= S; w++) { // j is max size of bag
if (c[i] > w) {
DP[i][w] = DP[i - 1][w];
} else {
DP[i][w] = max(DP[i - 1][w], v[i] + DP[i - 1][w - c[i]]);
}
}
}
cout << DP[N][S];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment