0/1背包问题(动态规划)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;

void print(vector<vector<int>> &v)
{
    for (int n = 0; n < v.size(); n++)
    {
        for (int c = 0; c < v[0].size(); c++)
        {
            cout << v[n][c] << " ";
        }
        cout << endl;
    }
}
int main()
{
    //0/1背包问题
    //最优子结构问题,即从子问题的最优解中找到全局问题的最优解
    //eg:
    /**(w=商品重量 v=商品价值)
     * 背包承载量:C=6
     * 商品个数:N=3
     * 商品1: w1=2 v1=1
     * 商品2: w2=3 v2=2
     * 商品3: w3=4 v3=4
     * */
    int N = 3;
    int C = 6;
    vector<int> w = {2, 3, 4};
    vector<int> v = {1, 2, 4};
    //创建二维表(用来记录在当前背包容量下,装入前i个商品的最大价值),顺便初始化
    vector<vector<int>> process(N + 1, vector<int>(C + 1, 0));
    //创建二维表(用来记录物品是否装入,装入为1,否则为0),顺便初始化
    vector<vector<int>> res(N + 1, vector<int>(C + 1, 0));
    for (int n = 1; n <= N; n++)
    {
        for (int c = 1; c <= C; c++)
        {
            int i = n - 1;
            // cout<<"n="<<n<<" c="<<c<<endl;
            // cout<<"w[i]="<<w[i]<<" v[i]="<<v[i]<<endl;
            // cout<<"process[n - 1][c - w[i]] + v[i]="<<(process[n - 1][c - w[i]] + v[i])<<" process[n - 1][c]="<<process[n - 1][c]<<endl;
            if (w[i] <= c && (process[n - 1][c - w[i]] + v[i]) > process[n - 1][c])
            {
                process[n][c] = process[n - 1][c - w[i]] + v[n - 1];
                res[n][c] = 1;
            }
            else
            {
                process[n][c] = process[n - 1][c];
            }
        }
        //print(res);
        cout << endl;
    }
//从最大值向前追溯,找到是哪些物品被放入背包
    int max = -1;
    int maxIndex = -1;
    for (int n = N; n >= 0; n--)
    {
        for (int c = C; c >=0; c--)
        {
            if (max < process[n][c])
                {
                    max = c;
                    maxIndex = n-1;
                }
        }
    }
    cout<<maxIndex<<endl;
    max-=w[maxIndex];
    for (int n = maxIndex-1; n >= 0; n--)
    {
        if(max==w[n]&&res[n+1][max]==1){
            cout<<n<<endl;
            max-=w[n];
        }
    }
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

365JHWZGo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值