分支界限法 解决0-1背包问题 C/C++代码实现

本文介绍了一种使用分支界限法求解0-1背包问题的C++代码实现,给定三个物品的体积和价值,背包容量为30,目标是找到最优组合以获得最大价值。
  1. 使用分支界限法解决0-1背包问题,物品的(体积:价值)分别为(16:45),(15:25),(15:25)。背包的容量为30,要求:将3个物品装入背包使其得到的价值最大

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

using namespace std;

struct Item {
    int weight;
    int value;

    Item(int w, int v) : weight(w), value(v) {}
};

bool compare(Item a, Item b) {
    double ratioA = (double)a.value / a.weight;
    double ratioB = (double)b.value / b.weight;
    return ratioA > ratioB;
}

int bound(int i, int weight, int value, vector<Item>& items, int capacity) {
    int boundValue = value;
    int totalWeight = weight;
    int n = items.size();

    while (i < n && totalWeight + items[i].weight <= capacity) {
        totalWeight += items[i].weight;
        boundValue += items[i].value;
        i++;
    }

    if (i < n) {
        double remainingWeight = capacity - totalWeight;
        boundValue +
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值