問題描述
有一個揹包,揹包容量是 M =150,有 7 個物品,物品可以分割成任意大小,要求儘可能讓裝入揹包中的物品總價值最大,但不能超過總容量
思路:按照物品性價比排序,性價比高的儘量多拿
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
//物品類
class Thing {
public:
double weight;//重量
double value;//總價值
double price;//單價
Thing(double w, double v) :weight(w), value(v) {
price = value / weight;
}
};
bool cmp(const Thing& t_1, const Thing& t_2) {
return t_1.price > t_2.price;
}
int main() {
double bagSize = 150;//揹包容量
double maxValue = 0;//最大價值
vector<double> v_weight = { 35, 30, 60, 50, 40, 10 };
vector<double> v_value = { 10, 40, 30, 50, 35, 40 };
vector<Thing> v_thing;
for (int i = 0; i < v_weight.size(); i++) {
Thing thing(v_weight[i], v_value[i]);
v_thing.push_back(thing);
}
sort(v_thing.begin(), v_thing.end(), cmp);
for (Thing t : v_thing) {
if (t.weight <= bagSize) {//全選
maxValue += t.value;
bagSize -= t.weight;
}
else {
maxValue += bagSize * t.price;
break;
}
}
cout << fixed << setprecision(2) << maxValue << endl;
return 0;
}