KNAPSACK PROBLEM


KNAPSACK PROBLEM USING GREEDY METHOD


#include<iostream.h>
#include<conio.h>
int i,j,n,temp=0,index[20]={0};
float p[20]={0},w[20]={0},x[20]={0},max,capacity;

void getdata()
{
cout<<"\nEnter the capacity of knapsack bag:";
cin>>max;
cout<<"\nEnter the number of objects:";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\nEnter the weight of objects {w[i]}"<<i+1,i+1;
cout<<":";
cin>>w[i];
cout<<"\nEnter the profit of object{p[i]}"<<i+1,i+1;
cout<<":";
cin>>p[i];
}
}

void knapsack(float p[],float w[],float x[],float max,int n)
{
for(i=0;i<n;index[temp]=i,i++)
for(temp=0,j=0;j<n;j++)
if((i!=j)&&(p[i]/w[i]<(p[j]/w[j])))
temp++;
capacity=max;
for(i=0;i<n;i++)
{
if(w[index[i]]>capacity)
break;
x[index[i]]=1.0;
capacity=capacity-w[index[i]];
}
if(i<n)
x[index[i]]=capacity/w[index[i]];
} 
void display()
{
float profit=0.0,max_cap=0.0;
for(i=0;i<n;i++)
profit=profit+x[i]*p[i];
for(i=0;i<n;i++)
max_cap=max_cap+w[i]*x[i];
cout<<"\nThe optimal solution Becomes";
cout<<"\nObject\tWeight\tProfit\tX\t";
cout<<"\n\t\tI\tw[i]\tp[i]\tx[i]\n\n";
for(i=0;i<n;i++)
cout<<"\n\t\t"<<w[i]<<"\t\t"<<p[i]<<"\t\t"<<x[i],i+1;
cout<<"\n\nTotal Profit of Knapsack is:"<<profit;
cout<<"\n\nTotal Weight of Knapsack is:"<<max_cap;
getch();
}

void main()
{
clrscr();
cout<<"\nKnapsack Problem using Greedy Method:";
getdata();
knapsack(p,w,x,max,n);
display();
getch();
}
 



OUTPUT:
           
           
Knapsack Problem using Greedy Method:
Enter the capacity of knapsack bag:6

Enter the number of objects:5

Enter the weight of objects {w[i]}1:3

Enter the profit of object{p[i]}1:25

Enter the weight of objects{w[i]}2:2

Enter the profit of object{p[i]}2:20

Enter the weight of objects{w[i]}3:1

Enter the profit of object{p[i]}3:15.

Enter the weight of objects {w[i]}4:4

Enter the profit of object{p[i]}4:40

Enter the weight of objects {w[i]}5:5

Enter the profit of object{p[i]}5:50

The optimal solution Becomes
          Object     Weight    Profit      X
                I            w[i]       p[i]       x[i]
                               3           25         0
                               2           20         0
                               1           15         1
                               4           40         0
                               5           50         1

Total Profit of Knapsack is: 65

Total Weight of Knapsack is: 6

 

Comments

Popular posts from this blog

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE

BOOKS DETAILS USING C STRUCTURE

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE