zoukankan      html  css  js  c++  java
  • 贪心策略 — 分数背包

      问题描述:体积分别为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
    

      

  • 相关阅读:
    券商
    养生之道
    房产买卖
    货币常识
    虚拟币
    其他开源项目
    Shiro
    文件上传插件
    JAVA常见问题
    如何写好PPT
  • 原文地址:https://www.cnblogs.com/darkchii/p/8594139.html
Copyright © 2011-2022 走看看