zcmu1368: Dynamic Programming (multiple backpacks)

Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1368

Topic

n kinds of items, backpack capacity w. Each item has a volume of wi, a value of vi, and ci. Seek the maximum value that the backpack can take.

范围:(1 <= n <= 100, 1 <= w <= 50000, 1 <= wi <= 10000, 1 <= vi <= 10000, 1 <= ci <= 200)

Ideas

Multiple backpack nude questions. When the total volume is greater than or equal to the backpack capacity, it conforms to a complete backpack. Otherwise, to meet the 01 backpack, it means to add the number ci as 1, 2, 4 and other binary numbers, such as 9=1+2+4+2, divide into four parts, double the volume value, and then perform the 01 backpack operation.

ac code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e5 + 5;
int dp[maxn];
int weight[maxn], value[maxn], num[maxn];
int n, s;
void bag1(int w, int v){ //01背包
    for(int i = s; i >= w; i --)
        dp[i] = max(dp[i], dp[i - w] + v);
}
void bag2(int w, int v){ //完全背包
    for(int i = w; i <= s; i ++)
        dp[i] = max(dp[i], dp[i - w] + v);
}
void bag3(int w, int v, int num){ //多重背包
    if(num * w >= s) bag2(w, v);
    else{
        int k = 1;
        while(k <= num){
            bag1(k * w, k * v);
            num -= k;
            k <<= 1;
        }
        bag1(num * w, num * v); //最后剩下的
    }
}
int main(){
    while(~scanf("%d%d", &n, &s)){
        for(int i = 1; i <= n; i ++){
            scanf("%d%d%d", &weight[i], &value[i], &num[i]);
        }
        memset(dp, 0, sizeof(dp));
        for(int i = 1; i <= n; i ++){
            bag3(weight[i], value[i], num[i]); //对每种物品做多重背包
        }
        printf("%d\n", dp[s]);
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_43911947/article/details/113361733