7.knapsack Using Greedy Method
7.knapsack Using Greedy Method
#include<iostream.h>
#include<conio.h>
float x[20],tp=0;
float i,j,u;
u=capacity;
for(i=0;i<n;i++)
x[i]=0.0;
for(i=0;i<n;i++)
if(weight[i]>u)
break;
else
x[i]=1.0;
tp=tp+profit[i];
u=u-weight[i];
if(i<n)
x[i]=u/weight[i];
tp=tp+(x[i]*profit[i]);
cout.precision(4);
cout<<x[i];
getch();
void main()
clrscr();
float weight[20],profit[20],capacity;
float num,i,j;
float ratio[20],temp;
cin>>num;
for(i=0;i<num;i++)
cin>>weight[i]>>profit[i];
cin>>capacity;
for(i=0;i<num;i++)
ratio[i]=profit[i]/weight[i];
}
for(i=0;i<num;i++)
for(j=j+1;j<num;j++)
if(ratio[i]<ratio[j])
temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;
temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;
temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
knapsack(num,weight,profit,capacity);