01背包用回溯算法40行代码解决

该程序使用C++编程,通过回溯法解决0-1背包问题,寻找在不超过给定重量限制(Mweight)的情况下,能获得的最大商品价值(Max)。程序读取商品价格(value)、重量(weight)及数量(n),并记录商品是否被选择(history),最终输出最大价值。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<cstring>
using namespace std;
int n;
int Max = 0;
//记录重量
int res = 0;
//记录不可超重
int Mweight;
int value[100];
int weight[100];
int history[100];
void Backtrack(int t){
    if(t>n){
        //记录价格
        int coins = 0;
        for(int i = 1;i<=n;i++){
            coins+=value[i]*history[i];
        }
        Max = Max>coins?Max:coins;
        return;
    }
    res += weight[t];
    history[t] = 1;
    if(res<=Mweight)Backtrack(t+1);
    res -= weight[t];
    history[t] = 0;
    Backtrack(t+1);
}
using namespace std;
int main(){
    cin>>n;
    cin>>Mweight;
    for(int i = 1;i<=n;i++){
        cin>>value[i]>>weight[i];
    }
    memset(history,0,sizeof history);
    Backtrack(1);
    cout<<Max<<endl;
    return 0;
}

value是商品价格

history是商品是否加入

weight是商品重量

Max是满足不超过Mweight情况下的最大价值取值

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值