主要思想先放价值比最大的物品,再按比例放价值比小的物品。
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct{
float w,x,v;
}Bag;
bool cmp(const Bag &a,const Bag &b){
float m=a.v/a.w;
float n=b.v/b.w;
if(m>=n)
return true;
else return false;
}
float Knapsack(Bag bag[],float C,int n){
int total,i;
for(i=0;i<n;i++){
bag[i].x=0;
}
i=1;
total=0;
while(bag[i].w<C){
bag[i].x=1;
// cout<<bag[i].x<<” “;
total=total+bag[i].v;
C=C-bag[i].w;
i++;
}
bag[i].x=C/bag[i].w;
for(int i=n;i>=1;i–){
cout<<bag[i].x<<” “;
}
total=total+bag[i].x*bag[i].v;
return total;
}
int main(){
Bag *bag=new Bag[20];
float C;
int n;
cout<<“Please input bag’s weight and bag’s n:”<<endl;
cin>>C>>n;
cout<<“Input weight and value:”<<endl;
for(int i=1;i<=n;i++){
cin>>bag[i].w>>bag[i].v;
}
cout<<endl;
sort(bag+1,bag+n+1,cmp);
// for(int i=1;i<=n;i++){
// cout<<bag[i].w<<” “<<bag[i].v<<endl;
// }
cout<<endl;
cout<<“重量:”<<Knapsack(bag,C,n);
}