-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathknapsack.cpp
More file actions
109 lines (103 loc) · 2.57 KB
/
knapsack.cpp
File metadata and controls
109 lines (103 loc) · 2.57 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
#include <bits/stdc++.h>
using namespace std;
int knapSackRecursive(int val[], int wt[], int n, int capacity)
{
// base condition
// we know that when array size is 0 or there is 0 capacity
// we have no profit
if (n == 0 || capacity == 0)
{
return 0;
}
// choice diagram
if (wt[n - 1] <= capacity)
{
return max(val[n - 1] + knapSackRecursive(val, wt, n - 1, capacity - wt[n - 1]), knapSackRecursive(val, wt, n - 1, capacity));
}
else
{
return knapSackRecursive(val, wt, n - 1, capacity);
}
}
int DP[100][1002];
int knapSackMemo(int val[], int wt[], int n, int capacity)
{
if (n == 0 || capacity == 0)
{
return 0;
}
if (DP[n][capacity] != -1)
{
return DP[n][capacity];
}
// choice diagram
if (wt[n - 1] <= capacity)
{
return DP[n][capacity] = max(val[n - 1] + knapSackMemo(val, wt, n - 1, capacity - wt[n - 1]), knapSackMemo(val, wt, n - 1, capacity));
}
else
{
return DP[n][capacity] = knapSackMemo(val, wt, n - 1, capacity);
}
}
int knapSackTabulation(int val[], int wt[], int n, int capacity)
{
int dp[n + 1][capacity + 1];
// base conditon(initialization)
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < capacity + 1; j++)
{
// change n with i
if (i == 0 || j == 0)
{
dp[i][j] = 0;
}
}
}
// choice diagram -- change n with i and capacity with k
for (int i = 1; i < n + 1; i++)
{
for (int j = 1; j < capacity + 1; j++)
{
if (wt[i - 1] <= j)
{
dp[i][j] = max(val[i - 1] + dp[i - 1][j - wt[i - 1]], dp[i - 1][j]);
}
else
{
// wt[i-1] > j
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n][capacity];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
int capacity;
cin >> capacity;
int wt[n], val[n];
for (int i = 0; i < n; i++)
{
cin >> wt[i];
}
for (int i = 0; i < n; i++)
{
cin >> val[i];
}
memset(DP, -1, sizeof(DP));
int maxProfitRecursive = knapSackRecursive(val, wt, n, capacity);
int maxProfitMemo = knapSackMemo(val, wt, n, capacity);
int maxProfitTabu = knapSackTabulation(val, wt, n, capacity);
cout << maxProfitRecursive << endl;
cout << maxProfitMemo << endl;
cout << maxProfitTabu << endl;
return 0;
}