-
Notifications
You must be signed in to change notification settings - Fork 0
/
knapsack problem.c
66 lines (62 loc) · 1.29 KB
/
knapsack problem.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
#include<stdio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]= {0};
int max(int i,int j) {
return ((i>j)?i:j);
}
void knap() {
int a,b;
int value;
for(i=1;i<=n;i++){
for(j=1;j<=cap;j++){
if(j<w[i])
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j],p[i]+v[i-1][j-w[i]]);
}
}
}
void main() {
int profit,count=0,i,j;
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("Enter the profit and weights of the elements\n");
for (i=1;i<=n;i++) {
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++){
if((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;
}
knap();
profit=v[n][cap];
for(i=0;i<=n;i++){
for(j=0;j<=cap;j++){
printf("%d\t",v[i][j]);
}
printf("\n");
}
//To find items
i=n;
j=cap;
while(j!=0&&i!=0) {
if(v[i][j]!=v[i-1][j]) {
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}
printf("Items included are\n");
printf("It no.\tweight\tprofit\n");
for (i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",i,w[i],p[i]);
printf("Total profit = %d\n",profit);
}