Skip to content

Commit 3b12d38

Browse files
authored
Merge pull request #501 from Shikha785/Shikha785-patch-2
Added a C program of Knapsack Problem
2 parents e14bf3f + 0622342 commit 3b12d38

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Knapsack_problem.c

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include<stdio.h>
2+
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
3+
int max(int i,int j)
4+
{
5+
return ((i>j)?i:j);
6+
}
7+
int knap(int i,int j){
8+
int value;
9+
if(v[i][j]<0){
10+
if(j<w[i])
11+
value=knap(i-1,j);
12+
else
13+
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
14+
v[i][j]=value;
15+
}
16+
return(v[i][j]);
17+
}
18+
int main(){
19+
int profit ,count=0;
20+
printf("\nEnter the number of objects ");
21+
scanf("%d",&n);
22+
printf("Enter the profit and weights of the elements \n ");
23+
for(i=1;i<=n;i++){
24+
printf("\nEnter profit and weight For object no %d :",i);
25+
scanf("%d%d",&p[i],&w[i]);
26+
}
27+
printf("\nEnter the capacity ");
28+
scanf("%d",&cap);
29+
for(i=0;i<=n;i++)
30+
for(j=0;j<=cap;j++)
31+
if((i==0)||(j==0))
32+
v[i][j]=0;
33+
else
34+
profit=knap(n,cap);
35+
i=n;
36+
j=cap;
37+
while(j!=0&&i!=0){
38+
v[i][j]=-1;
39+
if(v[i][j]!=v[i-1][j]){
40+
x[i]=1;
41+
j=j-w[i];
42+
i--;
43+
}
44+
else
45+
46+
i--;
47+
}
48+
printf("object included are \n ");
49+
printf("Sl.no\tweight\tprofit\n");
50+
for(i=1;i<=n;i++)
51+
if(x[i])
52+
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
53+
printf("Total profit = %d\n",profit);
54+
}

0 commit comments

Comments
 (0)