knapsack problem dynamic programming code example
Example 1: 0-1 knapsack problem dynamic programming using single array
int dp[MAXW];
int solve()
{
memset(dp, 0, sizeof(dp));
for(int i =1; i <= N; i++) {
for(int j = W; j >= 0; j--) {
dp[j] = (w[i] > j) ? dp[j]: max(dp[j], dp[j-w[i]] + v[i]);
}
}
return dp[W];
}
Example 2: knapsack
using namespace std;
vector<pair<int,int> >a;
//dp table is full of zeros
int n,s,dp[1002][1002];
void ini(){
for(int i=0;i<1002;i++)
for(int j=0;j<1002;j++)
dp[i][j]=-1;
}
int f(int x,int b){
//base solution
if(x>=n or b<=0)return 0;
//if we calculate this before, we just return the answer (value diferente of 0)
if(dp[x][b]!=-1)return dp[x][b];
//calculate de answer for x (position) and b(empty space in knapsack)
//we get max between take it or not and element, this gonna calculate all the
//posible combinations, with dp we won't calculate what is already calculated.
return dp[x][b]=max(f(x+1,b),b-a[x].second>=0?f(x+1,b-a[x].second)+a[x].first:INT_MIN);
}
int main(){
//fast scan and print
ios_base::sync_with_stdio(0);cin.tie(0);
//we obtain quantity of elements and size of knapsack
cin>>n>>s;
a.resize(n);
//we get value of elements
for(int i=0;i<n;i++)
cin>>a[i].first;
//we get size of elements
for(int i=0;i<n;i++)
cin>>a[i].second;
//initialize dp table
ini();
//print answer
cout<<f(0,s);
return 0;
}
Example 3: knapsack problem using dynamic approach inc++
using namespace std;
int max(int x, int y) {
return (x > y) ? x : y;
}
int knapSack(int W, int w[], int v[], int n) {
int i, wt;
int K[n + 1][W + 1];
for (i = 0; i <= n; i++) {
for (wt = 0; wt <= W; wt++) {
if (i == 0 || wt == 0)
K[i][wt] = 0;
else if (w[i - 1] <= wt)
K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]);
else
K[i][wt] = K[i - 1][wt];
}
}
return K[n][W];
}
int main() {
cout << "Enter the number of items in a Knapsack:";
int n, W;
cin >> n;
int v[n], w[n];
for (int i = 0; i < n; i++) {
cout << "Enter value and weight for item " << i << ":";
cin >> v[i];
cin >> w[i];
}
cout << "Enter the capacity of knapsack";
cin >> W;
cout << knapSack(W, w, v, n);
return 0;
}