小数背包问题
问题描述
有一个背包,背包容量是C,有N(1<N≤1000)个物品,每个物品右对应的价值val和重量weight。
要求尽可能让装入背中的物品总价值最大,但不能超过总容量。其中物品可以分割成任意大小。
小数背包与01背包
小数背包问题 | 0 1背包问题 |
---|---|
物品可拆分 | 物品是个不可分的整体 |
背包一定被装满 | 背包可能有空余 |
贪心算法 | DP算法 |
小数背包的贪心策略
- 选取贪心指标,即价值率val/weight
- 每次都选取价值率最大的物品进行装入
- 如果当前选取的物品可以放入背包(物品重量小于背包剩余容量),就直接装入,否则就将物品进行切割放入背包
代码
#include<iostream>
#include<algorithm>
using namespace std;
class item {
public:
int val=0;
int weight=0;
double rate=0;
friend bool operator<(const item& it1, const item& it2);
};
bool operator<(const item& it1, const item& it2) {
return it1.rate > it2.rate;
}
bool compare(const item& it1, const item& it2)
{
return it1 < it2;
}
void sol()
{
item a[3] = { {6,30},{2,20},{5,10} };
double res = 0;
int c = 20;//背包总容量
int left = c;//剩余容量
//求物品的价值率
for (int i = 0; i < 3; i++)
{
a[i].rate = static_cast<double>(a[i].val) / a[i].weight;
cout << "val:" << a[i].val << " weight:" << a[i].weight << " rate:" << a[i].rate << endl;
}
//按照价值率对物品进行从大到小排序
sort(a, a + 3, compare);
//每次都选择价值率较大者装入背包
for (int i = 0; i < 3; i++)
{
//如果当前物品能够被装入背包
if (a[i].weight <= left)
{
res += a[i].val;
left = c - a[i].weight;
}
else {//如果当前物品不能装入背包
res += a[i].rate * left;
}
}
cout << res << endl;
}
int main() {
sol();
return 0;
}
参考:
(贪心)小数背包问题、活动安排问题-CSDN博客