E - 划分(dp,二进制拆分)

https://vjudge.net/contest/279505#problem/E

现有面值为1、2、3、4、5、6的硬币若干枚,现在需要知道能不能将这些硬币分成等额的两堆。 

Input

每行输入6个正整数,分别表是面值为1、2、3、4、5、6的硬币的个数,若输入6个0代表输入结束。单种硬币的数量不会超过20000。

Output

若能分割,输出 ``Can be divided.'',若不能输出``Can't be divided.''

Sample Input

1 0 1 2 0 0
1 0 0 0 1 1
0 0 0 0 0 0

Sample Output

Collection #1:
Can't be divided.

Collection #2:
Can be divided.

题目大意:如上

题目分析:数据大直接01背包会TLE。采用二进制拆分,在01背包。

若f【sum/2】能从f【0】更新则 可分为两堆。

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#define INF 0x3f3f3f3f
using namespace std;
const int N=120005;
int dp[N];int f[N];
vector<int> v;
int main()
{
	int ct=0,a;
	while(1)
	{
		int sum=0;
		v.clear();
		memset(f,-INF,sizeof(f));
		for(int i=1;i<=6;i++)
		{
			scanf("%d",&a);
			sum+=a*i;
			for(int j=1;j<=a;j<<=1)
			{
				v.push_back(i*j);
				a-=j;
			}
			if(a>0)v.push_back(a*i);
		}
		if(sum==0)break;
		if(sum&1){
			printf("Collection #%d:\nCan't be divided.\n\n",++ct);
			continue;
		}
		f[0]=0;
		for(int i=0;i<v.size();i++){
			for(int j=sum/2;j>=v[i];j--){
				f[j]=max(f[j],f[j-v[i]]+v[i]);
			}
		}
		if(f[sum/2]<0)printf("Collection #%d:\nCan't be divided.\n\n",++ct);
		else printf("Collection #%d:\nCan be divided.\n\n",++ct);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_43490894/article/details/87560866
今日推荐