-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01knapsack.cpp
More file actions
49 lines (36 loc) · 735 Bytes
/
01knapsack.cpp
File metadata and controls
49 lines (36 loc) · 735 Bytes
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
#include <bits/stdc++.h>
int weight[100];
int value[100];
bool possible(int index, int wt) {
if (wt - weight[index] > 0) {
return true;
} else {
return false;
}
}
int knapsack(int index, int wt, int n) {
if (index <= n) {
return 0;
}
int max = INT_MIN;
if (possible(index, wt)) {
max = knapsack(index + 1, wt - weight[index], n) + value[index];
}
int max2;
max2 = knapsack(index + 1, wt, n);
if (max < max2) {
max = max2;
}
return max;
}
int main()
{
int n;
int wt;
scanf("%d", &wt);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d %d", &weight[i], &value[i]);
}
knapsack(0, wt, n);
}