背包问题 (二进制优化模版)

来源:互联网 发布:阿里云降价 编辑:程序博客网 时间:2024/06/07 22:57

51 nod
有N种物品,每种物品的数量为C1,C2……Cn。从中任选若干件放在容量为W的背包里,每种物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。
Input
第1行,2个整数,N和W中间用空格隔开。N为物品的种类,W为背包的容量。(1 <= N <= 100,1 <= W <= 50000)
第2 - N + 1行,每行3个整数,Wi,Pi和Ci分别是物品体积、价值和数量。(1 <= Wi, Pi <= 10000, 1 <= Ci <= 200)
Output
输出可以容纳的最大价值。
Input示例
3 6
2 2 5
3 3 8
1 4 1
Output示例
9

#include <cstdio>#include <cstring>#include <iostream>#include <cmath>#include <set>#include <algorithm>typedef long long ll;using namespace std;const int N=5e4+7;int dp[N]={0};int v;void com(int w,int p)//完全背包{    for(int j=w;j<=v;j++)        dp[j]=max(dp[j],dp[j-w]+p);}void zero(int w,int p)//01背包{    for(int j=v;j>=w;j--)        dp[j]=max(dp[j],dp[j-w]+p);}void add(int w,int p,int c){    if(c*w>=v)//完全背包    {        com(w,p);        return ;    }    int a=1;    while(c>a)//01背包二进制优化 将数字变为二进制相加,打包    {        c-=a;        zero(w*a,p*a);        a*=2;    }    zero(w*c,p*c);}int main(){    int n;    int w,p,c;    scanf("%d%d",&n,&v);    for(int i=0;i<n;i++)    {        scanf("%d%d%d",&w,&p,&c);        add(w,p,c);    }    printf("%d\n",dp[v]);}
1 0