-
Notifications
You must be signed in to change notification settings - Fork 18
/
Knapsack.cpp
58 lines (44 loc) · 1.27 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
// Knapsack with memoization
#include <iostream>
#include <vector>
using namespace std;
// Knapsack function
int knapsack(vector<int> &val, vector<int> &w, int n, int W,
vector<vector<int>> &memo)
{
// Base condition
if (n == 0 || W == 0)
return 0; // No profit made
// Check memo once before making recursive calls
if (memo[n][W] != -1)
return memo[n][W];
// Store result in memo instead of returning it directly
if (w[n - 1] <= W)
memo[n][W] = max(val[n - 1] + knapsack(val, w, n - 1, W - w[n - 1], memo),
knapsack(val, w, n - 1, W, memo));
else
memo[n][W] = knapsack(val, w, n - 1, W, memo);
return memo[n][W]; // And then return memo
}
int main()
{
int W; // Capacity of knapsack
int n; // Count of items
cout << "Enter the size of the array: ";
cin >> n;
vector<int> val(n);
vector<int> w(n);
cout << "Enter value array: ";
for (int i = 0; i < n; i++)
cin >> val[i];
cout << "Enter weight array: ";
for (int i = 0; i < n; i++)
cin >> w[i];
cout << "Enter capacity of Knapsack: ";
cin >> W;
// Memoize
vector<vector<int>> memo(
n + 1, vector<int>(W + 1, -1)); // Initialize all values with -1
cout << "Maximum profit: " << knapsack(val, w, n, W, memo) << "\n";
return 0;
}