Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
abdurrezzak authored Nov 8, 2017
1 parent 83e8fe0 commit 33e99ac
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions 17.Knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* This program solves 1/0 Knapsack program using Dynamic Programming
*
* Coded by: Abdurrezak EFE
* */

#include <iostream>
#include <algorithm>
#include <string>
#include <stdio.h>
using namespace std;

int d[10000][10000]={0}; //global dynamic programming table
int v[10000]={0};
int w[10000]={0};

int knapsack(int i, int j)
{
if(j<0)
return -10000000;

if(i <= 0 || j <= 0)
return 0;

if(d[i][j]) //if it was calculated return it
return d[i][j];

d[i][j] = max(knapsack(i-1, j), knapsack(i-1, j - w[i]) + v[i]); //memoizing the value

return d[i][j];
}

int main()
{
int n, m; //respectively size of the knapsack and number of items
cin >> n >> m;

for(int i=1;i<=n;i++)
cin >> v[i] >> w[i];

cout << knapsack(n,m);

}

0 comments on commit 33e99ac

Please sign in to comment.