问题描述:体积分别为10m3, 50m3, 80m3的箱子中装有价值分别为60w, 200w, 240w的珠宝,其中箱子的单位体积为10m3,也就是说体积为50m3的箱子中装有5个10m3的箱子,80m3的盒子中装有8个10m3的箱子。还有一个最多能装100m3的货车箱,请问如何装载装有珠宝的箱子可使得货车中的珠宝价值最大?
利用贪心,则很简单:
#include <iostream> #include <vector> using namespace std; class greedyAlgorithm { public: int fractionalKnapsack(vector<int> v, vector<int> w, int size) { int value = 0; int amount = 0; for (int i = 0; i < v.size(); i++) { if (amount > size) break; if (size - amount <= w[i]) value += v[i] * (size - amount) / w[i]; else value += v[i]; amount += w[i]; } return value; } }; int main() { vector<int> v{60, 200, 240}; vector<int> w{10, 50, 80}; greedyAlgorithm solve; cout << solve.fractionalKnapsack(v, w, 100); return 0; }
运行结果:
380