4-2 背包问题(贪心)
与0-1背包问题类似,所不同的只是在选择物品i装入背包时,可以选择物品的一部分而不一定要全部,1≤i≤n。
用贪心算法解背包问题的基本步骤是:
首先计算每种物品单位重量的价值vi/wi,然后,依贪心选择策略,将尽可能多的单位重量价值最高的物品装入背包。若将这种物品全部装入背包后,背包内的物品总重量未达到w,则选择单位重量价值次高的物品并尽可能多地装入背包。依此策略一直地进行下去直到背包满重为止。算法的主要计算时间在于将各种物品依其单位重量的价值从大到小排序。
因此,算法的计算时间上界为排序的时间复杂度O(nlogn)。
/*
20 6
3 6 2 5 5 10 1 2 6 16 4 8
*/
#include<iostream>
#include<algorithm>
using namespace std;
struct product{
int weight;
int value;
};
int comp(product a,product b){ //按value/weight从大到小排序
return a.value/a.weight > b.value/b.weight ;
}
int main(){
struct product p[10];
int i,c,n;
cin>>c>>n;
for(i=0;i<n;i++){
cin>>p[i].weight>>p[i].value;
}
sort(p,p+n,comp);
float t=c;//刚开始剩余容量为c
float ans=0;
float x[10];
for(i=0;i<n;i++) x[i]=0;
for(i=0;i<n;i++){
if(p[i].weight>t) break;
x[i]=1;
ans+=p[i].value;
t-=p[i].weight;
}
if(i<n){
x[i]=t/p[i].weight ;
ans+=t*p[i].value/p[i].weight ;
}
cout<<ans<<endl;
for(i=0;i<n;i++){
cout<<x[i]<<" ";
}
return 0;
}