一般背包问题(非0/1),找错
我调了半天看不出来,拿出来给大家看看吧,群众的眼睛是雪亮的。
//BackPack.h
class Object
{
public:
float value;
float weight;
};
#include<iostream>
#include"BackPack.h"
using namespace std;
void main()
{
float total=120;
float TotalValue=0;
Object obj[10]={50,17,60,30,70,25,80,41,90,80,80,70,70,64,60,56,50,47,40,38};
Object TempObj;
float xi[10]={0,0,0,0,0,0,0,0,0,0};
float price[10];
float temp[10];
float xch;
for(int i=0;i<10;i++)
{
price[i]=(obj[i].value)/(obj[i].weight);
temp[i]=price[i];
}
for(i=0;i<10;i++)
for(int j=i+1;j<10;j++)
{
if(temp[i]<temp[j])
{
xch=temp[i];
temp[i]=temp[j];
temp[j]=xch;
}
}
for(i=0;i<10;i++)
for(int j=0;j<10;j++)
{
if(price[j]==temp[i])
{
if(total>obj[j].weight)
{
xi[j]=1;
total=total-obj[j].weight;
TotalValue+=obj[j].value;
}
else
{
xi[j]=total/obj[j].weight;
TotalValue+=xi[j]*obj[j].value;
}
}
}
for(i=0;i<10;i++)
cout<<xi[i]<<endl;
cout<<TotalValue<<endl;
}