-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKnapSackDynamicProgramming.c
82 lines (79 loc) · 1.37 KB
/
KnapSackDynamicProgramming.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
#include<stdio.h>
#include<stdlib.h>
#define max 60//change size for bigger capacity
int max(int a,int b);
void knap(int n,int m, int w[max],int v[max][max],int p[max]);
void optimal(int n,int m,int w[max],int v[max][max],int p[max]);
int main()
{
int m,n,i,j,p[max],w[max],v[max][max];
printf("Enter no. of objects:");
scanf("%d",&n);
printf("Enter weight of %d objects:",n);
for (i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("Enter Profits:");
for (i=1;i<=n;i++)
scanf("%d",&p[i]);
printf("Enter capacity:");
scanf("%d",&m);
knap(n,m,w,v,p);
optimal(n,m,w,v,p);
return 0;
}
int max(int a,int b)
{
return (a>b?a:b);
}
void knap(int n,int m, int w[max],int v[max][max],int p[max])
{
int i,j;
for (i=0;i<=n;i++)
{
for (j=0;j<=m;j++)
{
if (i==0||j==0)
{
v[i][j]=0;
}
else if (w[i]>j)
{
v[i][j]=v[i-1][j];
}
else
{
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
}
printf("%d ",v[i][j]);
}
printf("\n");
}
}
void optimal(int n,int m,int w[max],int v[max][max],int p[max])
{
int i,j,x[max];
if (v[n][m]==0)
{
printf("Not possible!");
return;
}
printf("Optimal solution is :%d\n",v[n][m]);
for (i=0;i<n;i++)
{
x[i]=0;
}
i=n;
j=m;
printf("Objects selected: ");
while (i!=0 &&j!=0)
{
if (v[i][j]!=v[i-1][j])
{
x[i]=1;
printf("\nobject=%d,Weight=%d,profit=%d",i,w[i],p[i]);
j=j-w[i];
}
i=i-1;
}
printf("\n");
}