acwing 7 mixed backpack problem

Topic

Insert picture description here

answer

For the knapsack problem, we know that the update of each layer is only related to the previous layer, and has nothing to do with the type of backpack, so we only need to traverse one by one, and use what transfer equation to update what type of backpack we encounter.

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1100;

int n, m;
int f[N];


int main() {
    
    

    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
    
    
        int v, w, s;
        cin >> v >> w >> s;
        if (s == 0) {
    
       //完全背包
            for (int j = v; j <= m; j++) {
    
    
                f[j] = max(f[j], f[j - v] + w);
            }
        } else {
    
    
            if (s == -1) s = 1; //01背包看成使用1次的多重背包

            int k = 1;  //二进制优化多重背包
            while (k <= s) {
    
    
                for (int j = m; j >= k * v; j--) {
    
    
                    f[j] = max(f[j], f[j - k * v] + w * k);
                }
                s -= k;
                k*=2;
            }
            if (s) {
    
    
                for (int j = m; j >= s * v; j--) {
    
    
                    f[j] = max(f[j], f[j - s * v] + w * s);
                }
            }
        }
    }
    cout<<f[m]<<endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115335017