/*CSEMATTER.BLOGSPOT.IN
Program:C Program to implement fractional kanpsack*/
#include<stdio.h>
#include<conio.h>
int main()
{
float min(float ,float);
int i,j,n;
float p[20],w[20],v[20],sol[20],amt,W,temp,sum_sol=0.0;
printf("Enter the no. of entities ");
scanf("%d",&n);
printf("Enter the no. of entities of each items");
for(i=0; i<n; i++)
scanf("%f",&w[i]);
printf("Enter respective costs of entities");
for(i=0; i<n; i++)
scanf("%f",&v[i]);
printf("Enter the capacity of knapsack: ");
scanf("%f",&W);
for(i=0; i<n; i++)
p[i]=v[i]/w[i];
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(p[i]<p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=w[i];
w[i]=w[j];
w[j]=temp;
}
}
}
i=0;
while(W>0)
{
amt=min(W,w[i]);
sol[i]=amt;
W=W-amt;
i++;
}
printf("Solution array is :");
for(i=0; i<n; i++)
printf("%f \t",sol[i]);
for(i=0;i<n;i++)
sum_sol=sum_sol+sol[i];
printf("\n Hence maximum profit entity is: %f",sum_sol);
getch();
}
float min(float W,float a)
{
if(W>a)
return a;
else
return W;
}
/*OUTPUT:
Enter the no. of entities 5
Enter the no. of entities of each items5
10
20
30
40
Enter respective costs of entities30
20
100
90
160
Enter the capacity of knapsack: 60
Solution array is :5.000000 20.000000 35.000000 0.000000 0.000000
Hence maximum profit entity is: 60.000000 */
No comments:
Post a Comment