knapsack_Greedy
#include<stdio.h>
int main(){
float weight[100],profit[100],ratio[100],totalvalue=0,temp,capacity,amount;
int n,i,j;
printf("Enter the no of items:");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter the profit and weight: ");
scanf("%f%f",&profit[i],&weight[i]);
}
printf("Enter the capacity: ");
scanf("%f",&capacity);
for(i=0;i<n;i++){
ratio[i]= profit[i] / weight[i];
}
for(i=0;i<n;i++){
for(j=i+1;j<n;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;
}
}
}
printf("knapsack\n");
for(i=0;i<n;i++){
if(weight[i]> capacity){
break;
}
else{
totalvalue = totalvalue+ profit[i];
capacity = capacity - weight[i];
}
}
if(i<n)
totalvalue = totalvalue + (ratio[i] * capacity);
printf("max value is:%f",totalvalue);
return 0;
}
Comments
Post a Comment