Multiple backpack (binary Optimized)

Links: https://www.acwing.com/problem/content/5/

There are N kinds of goods and a capacity V  backpack.

The first article up to the i S i  pieces, each volume is V i , is the value of W i .

Which solving the items into the backpack, can not exceed the total volume of the article capacity of the backpack, and the sum of the maximum value.
The maximum output value.

Input Format

The first line of two integers, N , V , separated by spaces, each represent a kind of goods and a backpack volume.

Then there are N  rows, each row of three integers V I , W I , S I , separated by spaces, respectively denoteVolume of the i items, quantity and value.

Output Format

Output An integer representing the maximum value.

data range

0<N1000
0<V2000
0<vi,wi,si2000

prompt:

This title examines multiple binary optimization backpack.

SAMPLE INPUT

4 5
1 2 3
2 4 1
3 4 3
4 5 2

Sample output:

10


解题思路:把多重背包变成01背包
二进制优化:如果说把其物品都分成一分的话,会超时,
所以其子问题就是:一个数n,最少要多少个数才能把从1-n中的所有数表示出来;
答案是:log2(n)上取整个数
如:7的 1 2 4(2^0 2^1 2^2)
上面7是个特殊的例子:
再如10:如果用 1 2 4 8 表示的话会超过10
所以用1 2 4 3(10-1-2-4)
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 20110;
int v[N],w[N],s[N];
int dp[N];
int main()
{
    int n,m,v1,w1,s,cut=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>v1>>w1>>s;
        int k=1;
        while(k<=s){
            cut++;
            v[cut]=v1*k;
            w[cut]=w1*k;
            p - = a;
            k*=2;
        }
        if(s>0){
            cut++;
            v[cut]=v1*s;
            w[cut]=w1*s;
        }
    }
    n=cut;
    for(int i=1;i<=n;i++){
        for(int j=m;j>=v[i];j--){
            dp[j]=max(dp[j],dp[j-v[i]]+w[i]); 
        }
    }
    printf("%d",dp[m]);    
} 
View Code

 

 

Guess you like

Origin www.cnblogs.com/lipu123/p/12149851.html