-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathknapsack0-1.c
More file actions
59 lines (47 loc) · 1.08 KB
/
Copy pathknapsack0-1.c
File metadata and controls
59 lines (47 loc) · 1.08 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
#include<stdio.h>
void knapSack(int W, int n, int val[], int wt[]);
int getMax(int x, int y);
int main(void) {
//abcdefg
//the first element is set to -1 as
//we are storing item from index 1
//in val[] and wt[] array
int val[] = {-1, 100, 20, 60, 40}; //value of the items
int wt[] = {-1, 3, 2, 4, 1}; //weight of the items
int n = 4; //total items
int W = 5; //capacity of knapsack
knapSack(W, n, val, wt);
return 0;
}
int getMax(int x, int y) {
if(x > y) {
return x;
} else {
return y;
}
}
void knapSack(int W, int n, int val[], int wt[]) {
int i, w;
//value table having n+1 rows and W+1 columns
int V[n+1][W+1];
//fill the row i=0 with value 0
for(w = 0; w <= W; w++) {
V[0][w] = 0;
}
//fille the column w=0 with value 0
for(i = 0; i <= n; i++) {
V[i][0] = 0;
}
//fill the value table
for(i = 1; i <= n; i++) {
for(w = 1; w <= W; w++) {
if(wt[i] <= w) {
V[i][w] = getMax(V[i-1][w], val[i] + V[i-1][w - wt[i]]);
} else {
V[i][w] = V[i-1][w];
}
}
}
//max value that can be put inside the knapsack
printf("Max Value: %d\n", V[n][W]);
}