poj1014 (多重背包模板题)

模板

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)

代码:

#include<iostream>
#include<memory.h>
using namespace std;
int n[7];  //价值为i的物品的个数
int v;  //背包容量
int SumValue;  //物品总价值
bool flag;    //标记是否能平分SumValue
int dp[100000];  //状态数组

int max(int a,int b)
{
	return a>b?a:b;
}

/*完全背包*/
void CompletePack(int cost,int weight)
{
	for(int i=cost;i<=v;i++)
	{
		dp[i]=max(dp[i],dp[i-cost]+weight);
		if(dp[i]==v)    //剪枝,当能够平分SumValue时退出
		{
			flag=true;
			return;
		}
	}

	return;
}

/*01背包*/
void ZeroOnePack(int cost,int weight)
{
	for(int i=v;i>=cost;i--)
	{
		dp[i]=max(dp[i],dp[i-cost]+weight);
		if(dp[i]==v)    //剪枝
		{
			flag=true;
			return;
		}
	}
	return;
}

/*多重背包*/
void MultiplePack(int cost,int weight,int amount)
{
	if(cost*amount>=v)
	{
		CompletePack(cost,weight);
		return;
	}

	if(flag)    //剪枝
		return;

	/*二进制优化*/
	int k=1;
	while(k<amount)
	{
		ZeroOnePack(k*cost,k*weight);

		if(flag)    //剪枝
			return;

		amount-=k;
		k*=2;
	}
	ZeroOnePack(amount*cost,amount*weight);

	return;
}

int main()
{
    int i;
	int test=1;
	while(cin>>n[1]>>n[2]>>n[3]>>n[4]>>n[5]>>n[6])
	{
		SumValue=0;  //物品总价值

		for(i=1;i<=6;i++)
			SumValue+=i*n[i];

		if(SumValue==0)
			break;

		if(SumValue%2)    //sum为奇数,无法平分
		{
			cout<<"Collection #"<<test++<<':'<<endl;
			cout<<"Can't be divided."<<endl<<endl;
			continue;
		}

		v=SumValue/2;
		memset(dp,-1,sizeof(dp));
		dp[0]=0;
		flag=false;

		for(i=1;i<=6;i++)
		{
			MultiplePack(i,i,n[i]);

			if(flag)    //剪枝
				break;
		}

		if(flag)
		{
			cout<<"Collection #"<<test++<<':'<<endl;
			cout<<"Can be divided."<<endl<<endl;
			continue;
		}
		else
		{
			cout<<"Collection #"<<test++<<':'<<endl;
			cout<<"Can't be divided."<<endl<<endl;
			continue;
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值