多重背包的二进制优化模板

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 1000         //物品个数 
#define M 100000000    //所有物品可能的最大价值 
int m[N],c[N],w[N],f[M];
int V;
int max(int a,int b){return a>b?a:b;}
void ZeroOnePack(int cost,int weight)
{
    int v;
    for(v=V;v>=cost;v--) f[v]=max(f[v],f[v-cost]+weight);
}
void CompletePack(int cost,int weight)
{
    int v;
    for(v=cost;v<=V;v++)
        f[v]=max(f[v],f[v-cost]+weight);
}
void MultiplePack(int cost,int weight,int amount)
{
    int k;
    if(cost*amount>=V)
    {
        CompletePack(cost,weight);
        return;
    }
    k=1;
    while(k<amount)
    {
        ZeroOnePack(k*cost,k*weight);
        amount=amount-k;
        k=k*2;
    }
    ZeroOnePack(amount*cost,amount*weight);
}
int main()
{
    int n,i;
    scanf("%d %d",&n,&V);
                                                   // 两种不同的初始化方式,根据情况自行选择 
    //memset(f,0,sizeof(f[0])*(V+1));              // 只希望价格尽量大 
    //memset(f,-M,sizeof(f[0])*(V+1));f[0]=0;      // 要求恰好装满背包 
    for(i=0;i<n;i++) scanf("%d %d %d",m+i,c+i,w+i);
    for(i=0;i<n;i++) MultiplePack(c[i],w[i],m[i]);
    printf("%d\n",f[V]);
    system("PAUSE");
    return 0;
}

 

posted @ 2018-09-17 18:49  Chris-Zhang  阅读(362)  评论(0编辑  收藏  举报