-
Notifications
You must be signed in to change notification settings - Fork 1
/
0-1 knapsack.c
97 lines (73 loc) · 1.54 KB
/
0-1 knapsack.c
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
#include<stdio.h>
int main()
{
int n,flag[100]= {0},v[100],w[100],m[100][100],W,i,j,k;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the values: ");
for(i=1; i<=n; i++)
scanf("%d",&v[i]);
printf("Enter the weights: ");
for(i=1; i<=n; i++){
scanf("%d",&w[i]);
}
printf("Enter the capacity of knapsack: ");
scanf("%d",&W);
for(j=0; j<=W; j++){
m[0][j]=0;
}
for(i=1; i<=n; i++)
{
for(j=0; j<=W; j++)
{
if(w[i]<=j)
{
if( m[i-1][j] > (m[i-1][j-w[i]]+v[i]) )
m[i][j]=m[i-1][j];
else
m[i][j]=m[i-1][j-w[i]]+v[i];
}
else
m[i][j]=m[i-1][j];
}
}
i=n;
k=W;
while(i>0 && k>0)
{
if(m[i][k]!=m[i-1][k])
{
flag[i]=1;
k=k-w[i];
i=i-1;
}
else
i--;
}
printf("\n\t");
for(i=0; i<=W; i++){
printf("%d\t",i);
}
printf("\n");
for(i=0; i<=10*W; i++){
printf("-");
}
printf("\n");
for(i=0; i<=n; i++)
{
printf("%d |\t", i);
for(j=0; j<=W; j++){
printf("%d\t",m[i][j]);
}
printf("\n");
}
printf("\nThe resultant vector is ");
printf("( ");
for(i=1; i<=n; i++){
printf("%d ",flag[i]);
}
printf(")");
printf("\n\nThe total profit is %d",m[n][W]);
printf("\n");
return 0;
}