Tuesday, 8 October 2013

knapsack algorithm using c++


#include<iostream.h>
struct kru
{
  int i,p,w;
  float pr;

}g[10];
void main()
{

int n,j,k,wa;
float total=0;
struct kru temp;
cout<<"enter data ow W";
cin>>wa;
cout<<"Enter no.of nodes";
cin>>n;
cout<<"Enter for sum of calculation:";
for(j=0;j<n;j++)
{
g[j].i=j+1;
cout<<"i th profit =";
cin>>g[j].p;
cout<<"i th weight =";
cin>>g[j].w;
}
for(j=0;j<n;j++)
{
g[j].pr=g[j].p/float(g[j].w);
}
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
 if(g[j].pr<=g[k].pr)
 {
  temp=g[j];
  g[j]=g[k];
  g[k]=temp;

 }
}
}
for(j=0;j<n;j++)
{
  if(wa>=g[j].w)
  {
  total=total+g[j].p;
  wa=wa-g[j].w;
  }
  total=total+(g[j].pr*wa);
}
cout<<"total is "<<total;

}

No comments:

Post a Comment