-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack_Dynamic programming method.c
More file actions
68 lines (67 loc) · 1.04 KB
/
Knapsack_Dynamic programming method.c
File metadata and controls
68 lines (67 loc) · 1.04 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
#include<stdio.h>
#include<stdlib.h>
int *p,*w,n,m,*sel;
int max(int a,int b)
{
return a>b?a:b;
}
void knapsack()
{
int i,j,v[n+1][m+1];
for(i=0;i<=n;i++){
for(j=0;j<=m;j++){
if(i==0||j==0){
v[i][j]=0;
}
else 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]]) ;
}
}
}
printf("The table is:\n");
for(i=0;i<=n;i++){
for(j=0;j<=m;j++){
printf("%d\t",v[i][j]);
}
printf("\n");
}
printf("Maximum profit:%d\n",v[n][m]);
j=m;
for(i=n;i>=0;i--){
if(v[i][j]!=v[i-1][j]){
sel[i]=1;
j=j-w[i];
}
}
printf("The selected items are:\n");
for(i=1;i<=n;i++){
if(sel[i]==1){
printf("%d\t",i);
}
}
printf("\n");
}
int main()
{
int i;
printf("Number of items:");
scanf("%d",&n);
printf("Knapsack capacity:");
scanf("%d",&m);
p=calloc(n,sizeof(int));
w=calloc(n,sizeof(int));
sel=calloc(n,sizeof(int));
printf("Profit array:\n");
for(i=1;i<=n;i++){
scanf("%d",&p[i]);
}
printf("weight array:\n");
for(i=1;i<=n;i++){
scanf("%d",&w[i]);
}
knapsack();
return 0;
}