-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsack.CPP
More file actions
114 lines (87 loc) · 2.93 KB
/
knapsack.CPP
File metadata and controls
114 lines (87 loc) · 2.93 KB
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> knapsackContent(const vector<int> &val, const vector<int> &wt, const int &W){
int rows = val.size();
int cols = W + 1;
vector<vector<int>> T (rows, vector<int>( cols , 0 ));
for(int i=0; i<rows; ++i){
for(int j=1; j< cols; ++j){
// when considering item i of weight wt[i] and val[i] to fill the sack of capacity j
// we have two option either pick up the item i or do not pick up
// if you pick up the item, the sack is left with capacity : j-wt[i] and we already know how to fill it using earlier 0..(i-1) items.
if(i==0){
if(j>=wt[i])
T[0][j] = val[i];
continue;
}
if(j < wt[i])
T[i][j] = T[i-1][j];
else
T[i][j] = max(val[i] + T[i-1][j-wt[i]] , T[i-1][j]);
}
}
//-----------till now same as knapsack function
int MaxVal = T[rows-1][cols-1];
int totalwt = W;
vector<int> result;
int i=rows-1;
int j=cols-1;
while(MaxVal>0){
if(i==0){
if(MaxVal == val[0])
result.push_back(wt[0]);
}
if(i-1>=0){
if(T[i-1][j] == T[i][j]){
//the item is not selected
i = i-1;
continue;
}
else{
result.push_back(wt[i]);
j = totalwt - wt[i];
MaxVal -= val[i];
i = i-1;
}
}
}
return result;
}
int knapsack(const vector<int> &val, const vector<int> &wt, const int &W){
int rows = val.size();
int cols = W + 1;
vector<vector<int>> T (rows, vector<int>( cols , 0 ));
for(int i=0; i<rows; ++i){
for(int j=1; j< cols; ++j){
// when considering item i of weight wt[i] and val[i] to fill the sack of capacity j
// we have two option either pick up the item i or do not pick up
// if you pick up the item, the sack is left with capacity : j-wt[i] and we already know how to fill it using earlier 0..(i-1) items.
if(i==0){
if(j>=wt[i])
T[0][j] = val[i];
continue;
}
if(j < wt[i])
T[i][j] = T[i-1][j];
else
T[i][j] = max(val[i] + T[i-1][j-wt[i]] , T[i-1][j]);
}
}
for(int i=0; i<rows; ++i){
for(int j=0; j<cols; ++j){
cout << T[i][j] << " ";
}
cout << endl;
}
return T[rows-1][cols-1];
}
int main()
{
vector<int> val = {1,4,5,7};
vector<int> wt = {1,3,4,5};
int W = 7;
cout << knapsack(val,wt,W) << endl;
return 0;
}