Menu:

ADA (8) OOT (5)

Tuesday, April 12, 2016

Program for fractional Knapsack in C

#include<stdio.h>
int main()
{
int num,i,weight[20],price[20];
printf("Enter Total no of elements:-");
scanf("%d",&num);
printf("Enter weight and price:");
for(i=0;i<num;i++)
{
scanf("%d%d",&weight[i],&price[i]);
}
int value[20],temp,j;
for(i=0;i<num;i++)
{
value[i]=price[i]/weight[i];
}


for(i=0;i<num;i++)
{
for(j=i+1;j<num;j++)
{
if(value[i]<value[j])
{
temp=value[i];
value[i]=value[j];
value[j]=temp;

temp=weight[i];
weight[i]=weight[j];
weight[j]=temp;

temp=price[i];
price[i]=price[j];
price[j]=temp;
}
}
} //sorting done
for(i=0;i<num;i++)
{
printf("%d\t",weight[i]);
printf("%d\t",price[i]);
printf("%d\n",value[i]);
} //printing
int cap;
int knap[20];
int max=0;
int a=0;
int f=a;
printf("Enter capicity of knapsack:");
scanf("%d",&cap);

   for(i=0;i<num;i++)
   {
if(cap!=900)//for fractional
{
printf("\n");
f=a;
if(weight[i]<=cap)
{
printf("\nWEight:%d",weight[i]);
printf("\tIts value per ml:%d",value[i]);
for(j=a;j<f+weight[i];j++)                      //j is for inserting element in array just after previously inserted
{ //f is working as j.Because j goes incremented.
knap[j]=1;
printf("\n\tknap[%d]:%d",j+1,knap[j]);
cap--;
a++;
}
max=value[i]*weight[i]+max;
printf("\nInserted profit got :%d",price[i]);
weight[i]=0; //for fractional
} //Now for fractional:-
if(weight[i]>cap)
{ temp=cap;
printf("\nWEight:%d",weight[i]);
printf("\tIts value per ml:%d",value[i]);
printf("\nCapacity left in knap=%d",cap);
for(j=a;j<f+temp;j++) //here weight[i] is replaced by cap becoz weight is bigger than cap
{
knap[j]=1;
printf("\n\tknap[%d]:%d",j+1,knap[j]);
//temp because ca is decreased
cap--;
a++;
}
max=value[i]*temp+max;
printf("\nInserted profit got fractionly: %d",value[i]*temp);  //Here this is becoz we have to show all profit by
cap=900; //inserting fractional element
} //900 works as null
}
}

printf("\nMax price got:%d\n",max);
return 0;
}

No comments:

Post a Comment