KNAPSACK PROBLEM
#include”iostream.h”
#include”conio.h”
#include”process.h”
int Capacity;
int profit[40],weight[40],n;
float ratio[40],temp[40],temp1[40],soln[40];
class knapsack
{
public:
void getdata();
void sort();
void display();
void calculatesoln();
float getmaxprofit();
};
void knapsack::getdata()
{
clrscr();
cout<<"\nEnter the Capacity of Bag\n";
cin>>Capacity;
//cout<
cin>>n;
//cout<
for(int i=0;i
cout<
for(i=0;i
cout<
ratio[i]=(float)profit[i]/(float)weight[i];
temp[i]=ratio[i];
temp1[i]=ratio[i];
}
}
void knapsack::sort()
{
float t;
for(int i=0;i
for(int j=i+1;j
if(ratio[i]
t=ratio[i];
ratio[i]=ratio[j];
ratio[j]=t;
}
}
}
}
void knapsack::calculatesoln()
{
int maxcapac=0;
for(int i=0;i
for(int p=0;p
{
if((maxcapac+weight[p])<=Capacity)
{
soln[p]=1.0;
maxcapac+=weight[p];
temp[p]=-1.0;
}
/* else
{
soln[p]=(float)(Capacity-maxcapac)/weight[p];
maxcapac+=Capacity-maxcapac;
temp[p]=-1.0;
}*/
break;
}
if(maxcapac==Capacity)
break;
}
}
float knapsack::getmaxprofit()
{
knapsack k;
float maxprofit=0.0;
k.calculatesoln();
k.display();
for(int i=0;i
return maxprofit;
}
void knapsack::display()
{
clrscr();
cout<<"\nKNAPSACK PROBLEM\n";
cout<<"----------------";
cout<<"\nWeight of each Node\n";
for(int i=0;i
cout<<"\nProfit of each node\n";
for(i=0;i
cout<<"\n\n Profit Ratio Pi/Wi is\n\n";
for(i=0;i
for(i=0;i
cout<<"\nx"< }
}
void main()
{
clrscr();
knapsack kp;
kp.getdata();
kp.sort();
cout<<"\n\nMaximum Profit="<
}
OUTPUT:
KNAPSACK PROBLEM
Enter the Capacity of Bag
10
Enter the number of objects
5
Enter the profit
80
60
75
20
10
0
Enter the weight
2
1
5
2
2
KNAPSACK PROBLEM
Weight of each Node
2 1 5 2 2
Profit of each node
80 60 75 20 10
Profit Ratio Pi/Wi is
60 40 15 10 5
Values Profit/Weight
x0 1 40
x1 1 60
x2 1 15
x3 1 10
x4 0 5
Maximum Profit=235
No comments:
Post a Comment