-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapSackUnboundedLecture23.cpp
More file actions
96 lines (95 loc) · 2.35 KB
/
Copy pathKnapSackUnboundedLecture23.cpp
File metadata and controls
96 lines (95 loc) · 2.35 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
#include <vector>
#include <iostream>
using namespace std;
int solve1(int ind,int W, vector<int> &val, vector<int> &wt,vector<vector<int>> dp)
{
if(ind == 0)
{
return (int)(W/wt[0]) * val[0];
}
if(dp[ind][W] != -1) return dp[ind][W] ;
int notTake = solve1(ind-1,W,val,wt,dp);
int take = 0;
if(wt[ind] <= W)
{
take = val[ind] + solve1(ind,W-wt[ind],val,wt,dp);
}
return dp[ind][W] = max(take,notTake);
}
int solve2(int n, int w, vector<int> &val, vector<int> &wt)
{
vector<vector<int>> dp(n, vector<int>(w+1,-1));
for(int W = 0; W <= w;W++)
{
dp[0][W] = (int)(W/wt[0]) * val[0];
}
for(int ind = 1;ind <n;ind++)
{
for(int W = 0;W <= w;W++)
{
int notTake = dp[ind-1][W];
int take = 0;
if(wt[ind] <= W)
{
take = val[ind] + dp[ind][W-wt[ind]];
}
dp[ind][W] = max(take,notTake);
}
}
return dp[n-1][w];
}
int solve3(int n, int w, vector<int> &val, vector<int> &wt)
{
// vector<vector<int>> dp(n, vector<int>(w+1,-1));
vector<int> prev(w+1,0),cur(w+1,0);
for(int W = 0; W <= w;W++)
{
prev[W] = (int)(W/wt[0]) * val[0];
}
for(int ind = 1;ind <n;ind++)
{
for(int W = 0;W <= w;W++)
{
int notTake = prev[W];
int take = 0;
if(wt[ind] <= W)
{
take = val[ind] + cur[W-wt[ind]];
}
cur[W] = max(take,notTake);
}
prev = cur;
}
return prev[w];
}
int solve4(int n, int w, vector<int> &val, vector<int> &wt)
{
// Only 1 Extra array
vector<int> prev(w+1,0);
for(int W = 0; W <= w;W++)
{
prev[W] = (int)(W/wt[0]) * val[0];
}
for(int ind = 1;ind <n;ind++)
{
for(int W = 0;W <= w;W++)
{
int notTake = prev[W];
int take = 0;
if(wt[ind] <= W)
{
take = val[ind] + prev[W-wt[ind]];
}
prev[W] = max(take,notTake);
}
}
return prev[w];
}
int unboundedKnapsack(int n, int w, vector<int> &val, vector<int> &wt)
{
vector<vector<int>> dp(n, vector<int>(w+1,-1));
// return solve1(n-1,w,val,wt,dp);
// return solve2(n,w,val,wt);
// return solve3(n,w,val,wt);
return solve4(n,w,val,wt);
}