Program7 Greedy Knapsack
Program7 Greedy Knapsack
#include<stdio.h>
#define MAX 50
int p[MAX],w[MAX];
float x[MAX];
int n,m,i,j;
int main()
//clrscr();
scanf("%d",&n);
scanf("%d",&m);
for(i=0;i<n;i++)
scanf("%d",&p[i]);
for(i=0;i<n;i++)
scanf("%d",&w[i]);
greedyknapsack(n,w,p,m);
return 0;
getch();
double ratio[MAX],temp2;
int currentweight=0;
double maxprofit=0;
ratio[i]=(double)p[i]/w[i];
for(j=i+1; j<n;j++)
if(ratio[i]<ratio[j])
double temp=ratio[i];
ratio[i]=ratio[j];
ratio[j]=temp;
temp2=w[i];
w[i]=w[j];
w[j]=temp2;
temp2=p[i];
p[i]=p[j];
p[j]=temp2;
for(i=0;i<n;i++)
if(currentweight+w[i]<=m)
x[i]=1;
currentweight+=w[i];
maxprofit+=p[i];
}
else //Remove else part for Discrete Knapsack
x[i]=(m-currentweight)/(double)w[i];
maxprofit+=x[i]*p[i];
break;
for(i=0;i<n;i++)
printf("%f\t",x[i]);