-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path0-1_Knapsack_Problem.cpp
More file actions
42 lines (38 loc) · 895 Bytes
/
0-1_Knapsack_Problem.cpp
File metadata and controls
42 lines (38 loc) · 895 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;
int knapSack(int w, int wt[], int val[], int n)
{
vector<vector <int>> t;
for(int i = 0; i<n+1; i++)
{
vector <int> v;
for(int j = 0; j<w+1; j++)
{
if(i==0 || j==0)
v.push_back(0);
else
v.push_back(-1);
}
t.push_back(v);
}
for(int i = 1; i<n+1; i++)
{
for(int j = 1; j<w+1; j++)
{
if(wt[i-1] <= j)
{
t[i][j] = max(t[i-1][j], val[i-1] + t[i-1][j-wt[i-1]]);
}
else
{
t[i][j] = t[i-1][j];
}
}
}
return t[n][w];
}
int main()
{
int n = 3, w = 4, values[] = {1,2,3}, weights[] = {4,5,1};
cout<<knapSack(w, weights, values, n)<<endl;
}