0% found this document useful (0 votes)
40 views5 pages

Knapsack Backtracking

Uploaded by

kripalaalal4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views5 pages

Knapsack Backtracking

Uploaded by

kripalaalal4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

0/1 Knapsack Problem using 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 knapsack(int k,float cp,float cw)


{
int j;
if(cw+w[k] <= capacity)
{
y[k] = 1;
if(k < n-1)
knapsack(k+1,cp+p[k],cw+w[k]);
if(((cp+p[k]) > fp) && ( k == n-1))
{
fp = cp+p[k];
fw = cw+w[k];
for(j=0;j<=k;j++)
x[j] = y[j];
}
}
if(bound(cp,cw,k) >= fp)
{
y[k] = 0;
if( k <= n)
knapsack(k+1,cp,cw);
if((cp > fp) && (k == n-1))
{
fp = cp;
fw = cw;
for(j=0;j<=k;j++)
x[j] = y[j];
}
}
}

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

Item WeightProfit Ratio(p/w)


0 4 5 1.250000
1 5 6 1.200000
2 3 2 0.666667
3 2 1 0.500000
Solution is:
x[0]=0
x[1]=1
x[2]=1
x[3]=0
Maximum Profit: 8.000000

You might also like