PKU 1014 Dividing

题目:http://poj.org/problem?id=1014

题意:有6个物品,价值分别为1、2、3、4、5、6,输入6个数,代表相应的物品的个数,问的是 能不能物品分成两份,每份的价值总和相同。

思路:深搜或多重背包~~~

好久没写了  生啊~~~

//深搜
#include 
#include 

int array[10];
int a, b, c, d, e, f;
int sum;
int cnt, flag;
void dfs(int s, int x)
{
	if (flag==1) return;
	if (s==sum) {flag=1; return;}
	for (int i=x; i>=1; i--)
	{
		if (array[i]==0) continue;
		if (s+i<=sum) 
		{
			array[i]--;
			dfs(s+i, i);
			if (flag==1) return;
		}
	}
}

int main()
{
//	freopen("in.txt", "r", stdin);
	cnt=1;
	while (scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f)==6)
	{
		if (a==0&&b==0&&c==0&&d==0&&e==0&&f==0) break;
		printf("Collection #%d:\n", cnt++);
		memset(array, 0, sizeof(array));
		array[1]=a, array[2]=b, array[3]=c;
		array[4]=d, array[5]=e, array[6]=f;
		sum=1*a+2*b+3*c+4*d+5*e+6*f;
		if (sum%2) {printf("Can't be divided.\n\n"); continue;}
		sum/=2;
		flag=0;
		dfs(0, 6);
		if (flag==1) printf("Can be divided.\n\n");
		else  printf("Can't be divided.\n\n");
	}
	return 0;
}

//多重背包
#include 
#include 
const int maxn=200000;
int dp[maxn+10], num[10];
int value;
void CompletePacket(int c, int v)
{
	for (int i=c; i<=v; i++)
	{
		if (dp[i]<dp[i-c]+c&&dp[i-c]+c<=v) dp[i]=dp[i-c]+c;
	}
}
void ZeroOnePacket(int c, int v)
{
	for (int i=v; i>=c; i--)
	{
		if (dp[i]<dp[i-c]+c&&dp[i-c]+c<=v) dp[i]=dp[i-c]+c;
	}
}
void MulityPacket(int c, int v)
{
	for (int i=1; i<=c; i++)
	{
		if (num[i]==0) continue;
		if (num[i]*i>v) CompletePacket(i, v);
		else
		{
			int k=1;
			while (k<num[i])
			{
				ZeroOnePacket(k*i, v);
				num[i]=num[i]-k;
				k*=2;
			}
			ZeroOnePacket(num[i]*i, v);
		}
	}
}
int main()
{
//	freopen("in.txt", "r", stdin);
	int cnt=1;
	while (1)
	{
		value=0;
		for (int i=1; i<=6; i++) scanf("%d", &num[i]), value+=i*num[i];
		if (value==0) break;
		memset(dp, 0, sizeof(dp));
		printf("Collection #%d:\n", cnt++);
		if (value%2==1) {printf("Can't be divided.\n\n"); continue;}
		value=value/2;
		MulityPacket(6, value);
		if (dp[value]==value) printf("Can be divided.\n\n");
		else printf("Can't be divided.\n\n");
	}
	return 0;
}


你可能感兴趣的:(PKU,DP&贪心,DFS&BFS)