算法-背包问题

原型

Posted by MetaNetworks on November 5, 2019
本页面总访问量

参考:更详细的教程

附上自己的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * Problem: 背包问题
 * @Author: MetaNetworks
 * @Date: 2019-11-05 09:43:59
 * @LastEditors: MetaNetworks
 * @LastEditTime: 2019-11-05 11:42:30
 * @Description: MetaNetworks' Code
 */
#include <iostream>
#define itemNum 6 +1
#define PACK_VOL 12 +1
#define INITIAL_NUM -1
using namespace std;
// 容量
int vol[itemNum] = {0,4,6,2,2,5,1};
// 取值
int val[itemNum] = {0,8,10,6,3,7,2};
// 计算矩阵
int mat[itemNum][PACK_VOL];

int getVal(int itemNumber,int remainVOL){
    if (itemNumber <= 0 || remainVOL <= 0){
        return 0;
    }
    else
    {
        int v = mat[itemNumber][remainVOL];
        if (v != INITIAL_NUM){
            // 直接取值
            return v;
        }
        //分为两种情况,1.不可以装下  (2.1:可以装下但不装 2.2:可以装下,装)最大值
        if (remainVOL < vol[itemNumber]){
            // 不可用
            int iv = getVal(itemNumber-1,remainVOL);
            mat[itemNumber][remainVOL] = iv;
            return iv;
        }
        else{
            // return 1.不装 2.装下
            int iv =  max(
                getVal(itemNumber-1,remainVOL),
                getVal(itemNumber-1,remainVOL - vol[itemNumber]) + val[itemNumber]
            );
            mat[itemNumber][remainVOL] = iv;
            return iv;
        }
    }
}

void output(int itemNumber,int VOL){
    // 判断
    while (itemNumber > 0 && VOL > 0)
    {
        int maxn_1 = mat[itemNumber][VOL];
        int maxn_2 = mat[itemNumber-1][VOL];
        int maxn_3 = mat[itemNumber-1][VOL-vol[itemNumber]];
        // 考虑 未初始化的情况
        if (maxn_2 == INITIAL_NUM && maxn_3 == INITIAL_NUM)
        {
            if (maxn_1 != 0)
            {
                cout<<itemNumber<<" ";
            }
        }
        else{
            if(maxn_1 == maxn_2){
                /* 不取 */
            }
            else{
                /* 取 */
                cout<<itemNumber<<" ";
                VOL -= vol[itemNumber];
            }
        }
        itemNumber -= 1;
    }
    cout<<endl;
}

int main(){
    // 初始化
    for (int i = 0; i < itemNum; i++)
        for (int j = 0; j < PACK_VOL; j++)
            mat[i][j] = INITIAL_NUM;
    // 计算
    cout<<getVal(itemNum-1,PACK_VOL-1)<<endl;
    // 输出结果
    output(itemNum-1,PACK_VOL-1);
}

输出

1
2
24s
3 2 1