回溯法解决01背包问题

#include <iostream>
using namespace std;

struct thing {
    int weight;//物品重量
    int value;//物品价值
    int number;//物品数量
};

thing things[10];//假设最多有10个物品

int thingsCount;//物品数量
int bagSize;//背包容量
int maxTotalValue;//最大总重量
int currentWeight;//当前重量
int currentValue;//当前价值
int currentPath[10];//存储当前路径
int bestPath[10];//存储最优路径
void bruteForce(int number) {//蛮力法,参数为物品序号
    if (number > thingsCount - 1) {//最内层函数的返回条件:当已经遍历到最后一个物品时
        if (currentValue > maxTotalValue) {//若当前重量更大,只有当前容量小于背包容量才可以更新
            maxTotalValue = currentValue;
            for (int i = 0; i < number; i++) {
                bestPath[i] = currentPath[i];//将当前路径用最优路径数组保存
            }
        }
    }
    else {
        for (int i = 1; i >= 0; i--) {
            currentPath[number] = i;
            if (i) {
                if (currentWeight + things[number].weight <= bagSize) {//满足条件才将物品装包,否则就不装包,直接“剪枝”
                    //序号为number+1的物品装入背包的情况
                    currentWeight += things[number].weight;
                    currentValue += things[number].value;
                    bruteForce(number + 1);//向下递归
                    currentWeight -= things[number].weight;
                    currentValue -= things[number].value;
                }
            }else {
                //序号为number+1的物品不装入背包的情况
                bruteForce(number + 1);//向下递归
            }
        }
    }
}

int main() {
    //初始化物品数、背包容量和物品数组
    cin >> thingsCount;
    cin >> bagSize;
    for (int i = 0; i < thingsCount; i++) {
        cin >> things[i].weight >> things[i].value;
    }
    //回溯法计算最优组合
    bruteForce(0);
    cout << maxTotalValue << endl;
    return 0;
}

//请输入物品数:4
//请输入背包容量:10
//请输入序号为1的物品的重量和价值 : 7 42
//请输入序号为2的物品的重量和价值 : 3 12
//请输入序号为3的物品的重量和价值 : 4 40
//请输入序号为4的物品的重量和价值 : 5 25

 

posted @ 2023-05-01 21:58  Jocelynn  阅读(118)  评论(0)    收藏  举报