Knapsack Backtracking
Knapsack Backtracking
#include <stdio.h>
int fp=-1,fw=0;
int p[10], w[10],capacity,n;
int y[10],x[10];
float ratio[10];
void sort()
{
int t,t1,i,j;
float t2;
for(i=0;i<n;i++)
ratio[i] = (float)p[i]/(float)w[i];
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(ratio[i] <ratio[j])
{
t2 = ratio[i];
ratio[i] = ratio[j];
ratio[j] = t2;
t = p[i];
p[i] = p[j];
p[j] = t;
t1 = w[i];
w[i] = w[j];
w[j] =t1;
}
}
}
}
float bound(float cp,float cw,int k)
{
int i;
float b = cp;
float c = cw;
for(i=k;i<n;i++)
{
c = c+w[i];
if( c < capacity)
b = b +p[i];
else
return (b+(1-(c-capacity)/ (float)w[i])*p[i]);
}
return b;
}
void main()
{
int i;float s=0.0;
printf("Enter the number of objects: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\nEnter the profit of object %d:",i);
scanf("%d", &p[i]);
}
for (i = 0; i < n; i++)
{
printf("\nEnter the weight of object %d:",i);
scanf("%d", &w[i]);
}
printf("Enter the capacity of the knapsack: ");
scanf("%d", &capacity);
sort();
printf("\n\tItem\tWeight\tProfit\tRatio(p/w)\t" );
for(i=0;i<n;i++)
printf(“\n\t\t%d\t\t%d\t\t%d\t\t%f\t”,i,w[i],p[i],ratio[i]);
knapsack(0,0.0,0.0);
printf("\nSolution is:\n");
for(i=0;i<n;i++)
{
printf("x[%d]=%d\n",i,x[i]);
s += (float)p[i] * (float)x[i];
}
printf("\n Maximum Profit: %f ",s);
}
OUTPUT:
Enter the number of objects: 4
Enter the profit of object 0:1
Enter the profit of object 1:2
Enter the profit of object 2:5
Enter the profit of object 3:6
Enter the weight of object 0:2
Enter the weight of object 1:3
Enter the weight of object 2:4
Enter the weight of object 3:5
Enter the capacity of the knapsack: 8