-
Notifications
You must be signed in to change notification settings - Fork 2
/
knapsackDP.cpp
155 lines (58 loc) · 2.28 KB
/
knapsackDP.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include<bits/stdc++.h>
using namespace std;
int knapsack_dp(int n, int M, int w[], int p[])
{
int i,j;
//create a matrix to memoize the values using dynamic programming
int knapsack[n+1][M+1];
//knapsack[i][j] denotes the maximum attainable value of items in knpasack with i available
//items and capacity of knapsack being j
//initializing knapsack[0][j]=0 for 0<=j<=M
//because if there is no item, no value can be attained
for(j=0;j<=M;j++)
knapsack[0][j]=0;
//initializing knapsack[i][0]=0 for 0<=i<=n,
//because in a bag of zero capacity, no item can be placed
for(i=0;i<=n;i++)
knapsack[i][0]=0;
//now, filling the matrix in bottom up manner
for(i=1;i<=n;i++)
{
for(j=1;j<=M;j++)
{
//check if the weight of current item i is less than or equal to the capacity of sack,
//take maximum of once including the current item and once not including
if(w[i-1]<=j)
{
knapsack[i][j]=max(knapsack[i-1][j],p[i-1]+knapsack[i-1][j-w[i-1]]);
}
//can not include the current item in this case
else
{
knapsack[i][j]=knapsack[i-1][j];
}
}
}
return knapsack[n][M];
}
int main()
{
int i,j;
int n; //number of items
int M; //capacity of knapsack
cout<<"Enter the no. of items ";
cin>>n;
int w[n]; //weight of items
int p[n]; //value of items
cout<<"Enter the weight and price of all items"<<endl;
for(i=0;i<n;i++)
{
cin>>w[i]>>p[i];
}
cout<<"enter the capacity of knapsack ";
cin>>M;
int result=knapsack_dp(n,M,w,p);
//the maximum value will be given by knasack[n][M], ie. using n items with capacity M
cout<<"The maximum value of items that can be put into knapsack is "<<result;
return 0;
}