背包模版 自己用(hdu2844)

本文介绍了解决多重背包问题的一种高效算法实现,通过完全背包和0-1背包的组合使用来解决物品数量有限制的情况,并提供了详细的C语言代码实现。
#include<stdio.h>
#include<string.h>
struct node
{
    int value,number;
}a[110];
#define maxx 100010
int f[maxx];

/*
procedure MultiplePack(cost,weight,amount)
    if cost*amount>=V
        CompletePack(cost,weight)
        return
    integer k=1
    while k<amount
        ZeroOnePack(k*cost,k*weight)
        amount=amount-k
        k=k*2
    ZeroOnePack(amount*cost,amount*weight)
*/

int max(int x,int y)
{
 if(x>y)
 return x;
 return y;    
}
void Complete(int cost,int weight,int m)
{
    for(int i=cost;i<=m;i++)
        f[i]=max(f[i],f[i-weight]+cost);  
}


void Zero_One(int cost,int weight,int m)
{
        for(int i=m;i>=cost;i--)
          f[i]=max(f[i],f[i-weight]+cost);
}
void MultiplePack(int cost,int weight,int m,int number)
{
       // int t=a[i].value*a[i].number;
        if(weight*number>m)
            Complete(cost,weight,m);
        else
            {
                int k=1;
                while(k<number)
                {
                    Zero_One(k*cost,k*cost,m);
                    number-=k;
                    k<<=1;    
                }
                Zero_One(number*cost,number*cost,m);
             }
}
int main()
{
    int n,m,count,i,j,k,t;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0 && m==0)break;
        
        for(i=0;i<n;i++)
            scanf("%d",&a[i].value);
        for(i=0;i<n;i++)
            scanf("%d",&a[i].number);
        memset(f,0,sizeof(f));
        
        for(i=0;i<n;i++)
        {
            MultiplePack(a[i].value,a[i].value,m,a[i].number);
         }
          int ans=0;
          for(int i=1;i<=m;i++)
          {
                  if(f[i]==i)
                  ans++;
          }
        
        printf("%d\n",ans);
   }      
        
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值