-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_knapsack_top_down_II.cpp
More file actions
106 lines (104 loc) · 2.5 KB
/
01_knapsack_top_down_II.cpp
File metadata and controls
106 lines (104 loc) · 2.5 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
#include<iostream>
using namespace std;
int knapsack(int weight[],int value[],int W,int n)
{
if(n==0||W==0)
return 0;
else
{
//first if the weight of item is less than the weight that can be handled by knapsack then we may include other wise we will surely not
if(weight[n-1]<=W)
{
return max(value[n-1]+knapsack(weight,value,W-value[n-1],n-1),knapsack(weight,value,W,n-1));
}
else
return knapsack(weight,value,W,n-1);
}
}
int knapsack(int weight[],int value[],int W,int n,int **dp)
{
if(n==0 || W==0)
{
dp[n][W]=0;
return 0;
}
else if(dp[n][W]!=-1)
return dp[n][W];
else
{
if(weight[n-1]<=W)
{
dp[n][W]=max(value[n-1]+knapsack(weight,value,W-weight[n-1],n-1,dp),knapsack(weight,value,W,n-1,dp));
return dp[n][W];
}
else
{
dp[n][W]=knapsack(weight,value,W-weight[n-1],n-1,dp);
return dp[n][W];
}
}
}
int knapsack_top_down(int weight[],int value[],int n,int W)
{
int **dp=new int*[n+1];
for(int i=0;i<n+1;i++)
{
dp[i]=new int[W+1];
for(int j=0;j<W+1;j++)
dp[i][j]=0;
}
for(int i=1;i<n+1;i++)
{
for(int j=1;j<W+1;j++)
{
if(weight[i-1]<=j)
{
//if the weight of the item is less than the weight left to tear KnapSack
//then we will have two cases either we will include the item or discard
dp[i][j]=max(value[i-1]+dp[i-1][j-weight[i-1]],dp[i-1][j]);
}
else
{
//straight away we will discard it
dp[i][j]=dp[i-1][j];
}
}
}
return dp[n][W];
}
int main()
{
int n;
cout<<"Enter number of items : ";
cin>>n;
int weight[n];
int value[n];
int W;
cout<<"\nEnter total weight which the sack can handle : ";
cin>>W;
for(int i=0;i<n;i++)
{
cout<<"\nEnter price of items : ";
cin>>value[i];
}
for(int i=0;i<n;i++)
{
cout<<"\nEnter weight : ";
cin>>weight[i];
}
cout<<"\nFrom recursion : "<<knapsack(weight,value,W,n)<<endl;
int **dp=new int*[W+1];
for(int i=0;i<n+1;i++)
{ dp[i]=new int[W+1];
for(int j=0;j<W+1;j++)
dp[i][j]=-1;
}
cout<<"\nFrom memosization : "<<knapsack(weight,value,W,n,dp);
cout<<"\nFrom top-doen : "<<knapsack_top_down(weight,value,n,W);
}
/*
3
4
1 2 3
4 5 1
*/