(1)问题描述
给定几组数据,利用贪心算法的思想,将物品装入背包并使得其价值最大。
(2)实验步骤
① 计算每种物品单位重量的价值 Vi/Wi.
② 依贪心选择策略,将尽可能多的单位重量价值最高的物品装入背 包。
③ 若将这种物品全部装入背包后,背包内的物品总重量未超过 C, 则选择单位重量价值次高
的物品并尽可能多地装入背包。
④ 依此策略一直地进行下去,直到背包装满为止。
C++实现代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Thing{
int weight;
int value;
float per_v;
};
bool cmp(Thing a,Thing b){
return a.per_v>b.per_v;
}
int main(int argc, char** argv) {
int n;
cout<<"input the number of things:"<<endl;
cin>>n;
int c;
cout<<"input the capacity of the bag:"<<endl;
cin>>c;
Thing things[n];
for(int i=0;i<n;i++){
cin>>things[i].weight;
cin>>things[i].value;
things[i].per_v=things[i].value/things[i].weight;
}
sort(things,things+n,cmp);
for(int i=0;i<n;i++){
cout<<things[i].weight<<" ";
}
cout<<endl;
int i;
float sum=0;
for(i=0;i<n;i++){
if(things[i].weight<=c){
c-=things[i].weight;
sum+=things[i].value;
cout<<"价值"<<things[i].value<<"重量"<<things[i].weight<<"的物品装入背包"<<endl;
}else{
break;
}
}
if(i<n && c>0){
float rate=(float)c/(float)things[i].weight;
sum+=things[i].value*rate;
cout<<"价值"<<things[i].value<<"重量"<<things[i].weight<<"的物品装入背包,"<<"装入比例:"<<rate<<endl;
}
cout<<"装入背包物品总价值为:"<<sum<<endl;
system("pause");
return 0;
}