- 使用分支界限法解决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 +