forked from TheAlgorithms/C-Plus-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0-1 Knapsack.cpp
More file actions
71 lines (69 loc) · 1.31 KB
/
0-1 Knapsack.cpp
File metadata and controls
71 lines (69 loc) · 1.31 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
//0-1 Knapsack problem - Dynamic programming
//#include <bits/stdc++.h>
#include <iostream>
using namespace std;
//void Print(int res[20][20], int i, int j, int capacity)
//{
// if(i==0 || j==0)
// {
// return;
// }
// if(res[i-1][j]==res[i][j-1])
// {
// if(i<=capacity)
// {
// cout<<i<<" ";
// }
//
// Print(res, i-1, j-1, capacity-i);
// }
// else if(res[i-1][j]>res[i][j-1])
// {
// Print(res, i-1,j, capacity);
// }
// else if(res[i][j-1]>res[i-1][j])
// {
// Print(res, i,j-1, capacity);
// }
//}
int Knapsack(int capacity, int n, int weight[], int value[])
{
int res[20][20];
for (int i = 0; i < n + 1; ++i)
{
for (int j = 0; j < capacity + 1; ++j)
{
if (i == 0 || j == 0)
res[i][j] = 0;
else if (weight[i - 1] <= j)
res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]);
else
res[i][j] = res[i - 1][j];
}
}
// Print(res, n, capacity, capacity);
// cout<<"\n";
return res[n][capacity];
}
int main()
{
int n;
cout << "Enter number of items: ";
cin >> n;
int weight[n], value[n];
cout << "Enter weights: ";
for (int i = 0; i < n; ++i)
{
cin >> weight[i];
}
cout << "Enter values: ";
for (int i = 0; i < n; ++i)
{
cin >> value[i];
}
int capacity;
cout << "Enter capacity: ";
cin >> capacity;
cout << Knapsack(capacity, n, weight, value);
return 0;
}