Aim:Program For 0/1 Knapsack Problem Roll No.:104179
Aim:Program For 0/1 Knapsack Problem Roll No.:104179
Roll no.:104179
#include<stdio.h>
#include<conio.h>
void main()
{
float pw[20];
int i,j,k,temp,temp1,wt=0,pro=0,item[20],c=0;
int w[20],p[20],m,n;
clrscr();
printf("\nEnter the no. of items :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the weight and profit of %d
item ::",i+1);
scanf("%d%d",&w[i],&p[i]);
}
printf("\nEnter the capacity:");
scanf("%d",&m);
for(i=0;i<n;i++)
{
pw[i]=p[i]/w[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(pw[j]<pw[j+1])
{
temp=pw[j];
pw[j]=pw[j+1];
pw[j+1]=temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
temp1=w[j];
w[j]=w[j+1];
w[j+1]=temp1;
}
}
}
printf("\n\n\tweight\tprofit\tprofit/weight ");
for(i=0;i<n;i++)
{
printf("\n\n\t%4d\t%4d\t%4f",w[i],p[i],pw[i]);
}
i=0;
wt=0;
while(1)
{
if(wt>m)
break;
else
{
wt=wt+w[i];
pro=pro+p[i];
item[c]=i;
c++;
if(wt>m)
{
wt=wt-w[i];
pro=pro-p[i];
c--;
break;
}
if(wt==m)
{
break;
}
i++;
}
}
printf("\n\n\n\titem\tweight\tprofit");
for(i=0;i<c;i++)
{
j=item[i];
printf("\n\n\t%4d\t%4d\t%4d",item[i],w[j],p[j]);
}
printf("\n\n\tMax profit= %d",pro);
getch();
}
************** OUTPUT *****************
2 3 1.000000
3 4 1.000000
4 5 1.000000
5 6 1.000000
0 2 3
1 3 4
Max profit= 7