Last active
December 13, 2015 13:42
-
-
Save bruceoutdoors/615c7267a5cd8dcae5f7 to your computer and use it in GitHub Desktop.
Dynamic programming solution to http://www.spoj.com/problems/KNAPSACK/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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