-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0-1knapsack.cpp
76 lines (58 loc) · 1.34 KB
/
0-1knapsack.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<iostream>
#include<iomanip>
void knapSack(int, int , int[], int[]);
int getMax(int,int);
int main() {
//the first element is set to -1 as
//we are storing item from index 1
//in val[] and wt[] array
int val[] = {-1, 100, 20, 60, 40}; //value of the items
int wt[] = {-1, 3, 2, 4, 1}; //weight of the items
int n = 4; //total items
int W = 5; //capacity of knapsack
knapSack(W, n, val, wt);
return 0;
}
int getMax(int x, int y)
{
if(x > y)
{
return x;
} else
{
return y;
}
}
void knapSack(int W, int n, int val[], int wt[])
{
int i, w;
//value table having n+1 rows and W+1 columns
int V[n+1][W+1];
//fill the row i=0 with value 0
for(w = 0; w <= W; w++)
{
V[0][w] = 0;
}
//fille the column w=0 with value 0
for(i = 0; i <= n; i++)
{
V[i][0] = 0;
}
//fill the value table
for(i = 1; i <= n; i++)
{
for(w = 1; w <= W; w++)
{
if(wt[i] <= w)
{
V[i][w] = getMax(V[i-1][w], val[i] + V[i-1][w - wt[i]]);
}
else
{
V[i][w] = V[i-1][w];
}
}
}
//max value that can be put inside the knapsack
std::cout<<"Max Value: "<< V[n][W]<<std::endl;
}