【C++】最优装载问题

贪心算法——采用重量最轻者先装的贪心选择策略

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct {
    int id;
    int carry;
}Good;

bool compareGoods(const Good& a, const Good& b)  // 在algorithm里,前项小于后项
{
    return a.carry < b.carry;
}

void Greedy(vector<Good>& goods, int carrige)
{
    vector<Good> choosenGoods;
    sort(goods.begin(), goods.end(), compareGoods);  // 根据指定方式排序

    int currentWeight = 0;
    while(currentWeight < carrige && !goods.empty()){
        if (goods[0].carry > carrige-currentWeight) break;
        else{
            currentWeight += goods[0].carry;
            Good item = goods[0];
            goods.erase(goods.begin());  // 擦除某项,注意标号
            choosenGoods.push_back(item);// 引入某项
        }
    }
    cout << "There are " << choosenGoods.size() << " goods chosen" << endl << "Weight " << currentWeight << endl;
    cout << "They are ";
    for(Good i: choosenGoods){
        cout << i.id << " ";
    }
    cout << endl;
}

int main() {
    vector<Good> goods = {{1,5}, {2,4}, {3, 6}, {4,1}, {5, 10}};

    Greedy(goods, 13);
    return 0;
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
最优装载问题,也称为背包问题(Knapsack Problem),在计算机科学中是一个经典的组合优化问题,通常涉及到如何在给定容量限制下,选择物品以获得最大的价值。在C++中,解决这类问题的一种常见方法是使用贪心算法,特别是针对0-1背包问题(每个物品只能取一次)。 贪心算法策略是每次选择当前状态下能够提供最大收益(价值/重量比)的物品放入背包,直到达到背包的容量。以下是使用贪心策略解决0-1背包问题的一个简单C++实现: ```cpp #include <iostream> #include <vector> // 定义物品类 struct Item { int weight; // 重量 int value; // 价值 }; // 贪心函数,返回包含在背包中的最大总价值 int greedyKnapsack(std::vector<Item>& items, int capacity) { std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) { return (a.value / a.weight) > (b.value / b.weight); }); // 按价值/重量比率排序 int totalValue = 0; for (const auto& item : items) { if (capacity >= item.weight) { // 如果有足够空间,添加当前物品 totalValue += item.value; capacity -= item.weight; // 更新背包容量 } else { // 如果超出容量,选择部分物品 totalValue += item.value * (capacity / item.weight); break; // 停止添加,因为剩余容量不足以再放一个完整的物品 } } return totalValue; } int main() { std::vector<Item> items = {{60, 100}, {100, 200}, {120, 300}}; // 一些物品及其重量和价值 int capacity = 500; // 背包容量 int maxTotalValue = greedyKnapsack(items, capacity); std::cout << "Max total value with greedy approach: " << maxTotalValue << std::endl; return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值