KNAPSACK PROBLEM USING BACKTRACKING METHOD



KNAPSACK PROBLEM USING BACKTRACKING METHOD


#include<iostream.h>
#include<conio.h>
#include<math.h>
float p[10]={0},w[10]={0},y[10]={0},x[10]={0};
int i,n,max,k,cp=0,cw=0,fp,fw;
class back
{
public:
void get();
void knapsack(int,int,int);
int bound(int,int,int);
};
void back::get()
{
int i;
cout<<"\nEnter the Capacity:";
cin>>max;
cout<<"\n\nEnter the no.of Object:";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"Enter the weight of the object{w}"<<i,i;
cout<<":";
cin>>w[i];
cout<<"Enter the profit of the object{p}"<<i,i;
cout<<":";
cin>>p[i];
}
}
void back::knapsack(int k,int cp,int cw)
{
int j;
if(cw+w[k],+max)
{
y[k]=1;
if(k<n)
knapsack(k+1,cp+p[k],cw+w[k]);
if((cp+p[k]>fp)&&(k==n))
{
fp=cp+p[k];
fw=cw+w[k];
for(j=1;j<=n;++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))
{
fp=cp;
fw=cw;
for(j=1;j<=n;j++)
x[j]=y[j];
}
}
}
int back::bound(int cp,int cw,int k)
{
int i,b,c;
b=cp;
c=cw;
for(i=k+1;i<=n;i++)
{
c=c+w[i];
if(c<max)
b=b+p[i];
else
{
return(b+(1-(c-max)/w[i])*p[i]);
}
}
return b;
}
void main()
{
clrscr();
cout<<"\n\n\tKnapsack Using Backtracking\n";
back obj;
obj.get();
k=1;
cp=0;
cw=0;
obj.knapsack(k,cp,cw);
cout<<"\nSelected Object are:\n";
for(i=1;i<=n;i++)
{
if(x[i]==1)
cout<<"\nObject :"<<" "<<i;
}
cout<<"\nMax Profit of the knapsack is:"<<fp;
cout<<"\nTotal weight of the knapsack is:"<<fw;
getch();
}



OUTPUT:
           
           
                 Knapsack Using Backtracking

Enter the Capacity:20


Enter the no.of Object:3
Enter the weight of the object{w}1:20
Enter the profit of the object{p}1:34
Enter the weight of the object{w}2:25
Enter the profit of the object{p}2:39
Enter the weight of the object{w}3:13
Enter the profit of the object{p}3:44

Selected Object are:

Object : 1
Object : 2
Object : 3
Max Profit of the knapsack is:117
Total weight of the knapsack is:58
 



Comments

  1. could you put the steps in doing this sir?or lets just say its backtracking algorithm steps sir?

    ReplyDelete
  2. if you are not wrong ? Capacity knpsack written here is 20 , why did you take all of the objects There ? :)

    ReplyDelete

Post a Comment

Popular posts from this blog

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE

BOOKS DETAILS USING C STRUCTURE

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE