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
    

      

  • 相关阅读:
    运算符优先级
    Tips—查询某结构体
    在线词典--(一、流程分析)
    数据库—SQLite3
    回调函数(转载)
    UNIX域套接字
    进程间通信小结
    HDU_oj_2027 统计元音
    HDU_oj_2026 首字母变大写
    HDU_oj_2025 查找最大字母
  • 原文地址:https://www.cnblogs.com/darkchii/p/8594139.html
Copyright © 2011-2022 走看看