poj 1014 Dividing 多重背包

题意:价值为1~6的弹珠各有若干个,问能否按价值均分

思路:多重背包,V为总价值的一半,若dp[V] == V,则能均分

#include
using namespace std;
#define max(a,b) ((a)>(b)?(a):(b))
void ZeroOnePack(int weight,int value,int V,int dp[])
{
	for(int v = V;v >= weight;v--)
		dp[v] = max(dp[v],dp[v-weight]+value);
}
void CompletePack(int weight,int value,int V,int dp[])
{
	for(int v = weight;v <= V;v++)
		dp[v] = max(dp[v],dp[v-weight]+value);
}
void MultiplePack(int weight,int value,int count,int V,int dp[])
{
	if(weight*count >= V)
		CompletePack(weight,value,V,dp);
	else
	{
		int k = 1;
		while(k < count)
		{
			ZeroOnePack(k*weight,k*value,V,dp);
			count -= k;
			k = k*2;
		}
		ZeroOnePack(count*weight,count*value,V,dp);
	}
}
int main()
{
	int v[6],total = 1,dp[60005];
	while(scanf("%d %d %d %d %d %d",&v[0],&v[1],&v[2],&v[3],&v[4],&v[5]))
	{
		int i,sum = 0;
		for(i = 0;i < 6;i++)
			sum += v[i]*(i+1);
		if(sum == 0) break;
		memset(dp,0,sizeof(dp));
		printf("Collection #%d:\n",total++);
		if(sum%2 == 1)
		{
			printf("Can't be divided.\n");
			printf("\n");
			continue;
		}
		sum = sum/2;
		for(i = 0;i < 6;i++)
			MultiplePack(i+1,i+1,v[i],sum,dp);
		if(dp[sum] == sum) //若刚好等于平均值,则说明可以均分
			printf("Can be divided.\n");
		else
			printf("Can't be divided.\n");
		printf("\n");
	}
	return 0;
}


你可能感兴趣的:(DP,背包问题)