forked from shivprime94/Data-Structure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsack.c
More file actions
48 lines (44 loc) · 903 Bytes
/
knapsack.c
File metadata and controls
48 lines (44 loc) · 903 Bytes
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
#include<stdio.h>
int max(int a,int b);
int v[20][20];
int main()
{
int i,j,p[20],w[20],n,total;
printf("Enter the number of items\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the weight and profit of the item %d:\n",i);
scanf("%d %d",&w[i],&p[i]);
}
printf("Enter the capacity of the knapsack:\n");
scanf("%d",&total);
for(i=0;i<=n;i++)
v[i][0]=0;
for(j=0;j<=total;j++)
v[0][j]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=total;j++)
{
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("\nThe maximum profit is %d",v[n][total]);
printf("\nThe items selected are:");
j=total;
for(i=n;i>=1;i--)
if(v[i][j]!=v[i-1][j])
{
printf("\titem %d ",i);
j=j-w[i];
}
return 0;
}
int max(int a,int b)
{
return(a>b)?a:b;
}