-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknapsack.cpp
92 lines (68 loc) · 1.22 KB
/
knapsack.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
//19th July 2024
//0-1 Knapsack using dp
#include<iostream>
using namespace std;
void knapsack(int P[],int V[],int n,int W){
cout<<"KnapSack\n";
int k[n+1][W+1];
for(int i=0;i<=n;i++){
for(int j=0;j<=W;j++){
if(i==0 || j==0){
k[i][j] = 0;
}
else if(j >= V[i-1]){
k[i][j] = max(k[i-1][j],P[i-1]+k[i-1][j-V[i-1]]);
}
else{
k[i][j] = k[i-1][j];
}
}
}
//cout<<"Max Profit = "<<k[n][W]<<"\n";
cout<<"\nDP Table\n";
for(int i=0;i<=n;i++){
for(int j=0;j<=W;j++){
cout<<k[i][j]<<" ";
}
cout<<"\n";
}
//cout<<"\nMax Profit = "<<k[n][W]<<"\n";
//Included Elements:
int x[n];
int i=n , j=W;
while(i>0 && j>=0){
if(k[i][j] == k[i-1][j]){
x[i-1] = 0;
i--;
}else{
x[i-1] = 1;
j = j - V[i-1];
i--;
}
}
cout<<"\n0/1 Knapsack : \n";
cout<<"P\t:\t";
for(int i=0;i<n;i++){
cout<<P[i]<<"\t";
}
cout<<"\n";
cout<<"V\t:\t";
for(int i=0;i<n;i++){
cout<<V[i]<<"\t";
}
cout<<"\n";
cout<<"0/1\t:\t";
for(int i=0;i<n;i++){
cout<<x[i]<<"\t";
}
cout<<"\n";
cout<<"Max Profit = "<<k[n][W]<<"\n";
cout<<"Capacity = "<<W<<"\n";
}
int main(){
int n=4;
int P[]={2,5,1,9};
int V[]={1,2,3,4};
int W = 5;
knapsack(P,V,n,W);
}