C/C++ 实现贪心算法 解决背包问题

使用贪心算法解决背包问题,物品的(体积:价值)分别为{2, 3}, {3, 6}, {4, 9}, {2, 7}。背包的容量为5,要求:将4个物品装入背包使其得到的价值最大。

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

using namespace std;

struct Item {
    int weight;
    int value;
};

bool compare(Item item1, Item item2) {
    double ratio1 = (double)item1.value / item1.weight;
    double ratio2 = (double)item2.value / item2.weight;
    return ratio1 > ratio2;
}

int knapsack(int capacity, vector<Item>& items) {
    sort(items.begin(), items.end(), compare);

    int totalValue = 0;
    int currentWeight = 0;

    for (int i = 0; i < items.size(); i++) {
        if (currentWeight + items[i].weight <= capacity) {
            currentWeight += items[i].weight;
            totalValue += items[i].value;
        }
    }

    return totalValue;
}

int main() {
    Item item1;
    item1.weight = 2;
    item1.value = 3;
    Item item2;
    item2.weight = 3;
    item2.value = 6;
    Item item3;
    item3.weight = 4;
    item3.value = 9;
    Item item4;
    item4.weight = 2;
    item4.value = 7;
    vector<Item> items;
    items.push_back(item1);
    items.push_back(item2);
    items.push_back(item3);
    items.push_back(item4);

    int capacity = 5;

    int maxValue = knapsack(capacity, items);

    cout << "Max value: " << maxValue << endl;

    return 0;
}

 

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值