【POJ 1014】【Dividing】

题目:

Marsha and Bill own a collection of marbles. They want to split the collection among themselves so that both receive an equal share of the marbles. This would be easy if all the marbles had the same value, because then they could just split the collection in half. But unfortunately, some of the marbles are larger, or more beautiful than others. So, Marsha and Bill start by assigning a value, a natural number between one and six, to each marble. Now they want to divide the marbles so that each of them gets the same total value. Unfortunately, they realize that it might be impossible to divide the marbles in this way (even if the total value of all marbles is even). For example, if there are one marble of value 1, one of value 3 and two of value 4, then they cannot be split into sets of equal value. So, they ask you to write a program that checks whether there is a fair partition of the marbles.

Input

Each line in the input file describes one collection of marbles to be divided. The lines contain six non-negative integers n1 , . . . , n6 , where ni is the number of marbles of value i. So, the example from above would be described by the input-line "1 0 1 2 0 0". The maximum total number of marbles will be 20000. 
The last line of the input file will be "0 0 0 0 0 0"; do not process this line.

Output

For each collection, output "Collection #k:", where k is the number of the test case, and then either "Can be divided." or "Can't be divided.". 
Output a blank line after each test case.

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.

题意:两个人拥有一定数量的有价值的石头,并且是不可分割的,按照给的顺序,第几位的石头拥有的价值是相应位置的序列,即第一个数字对应石头的价值为1,一次类推,第六个为6.然后 他俩生气了,要分家产了,咳咳咳,假设他俩为情侣,如果能够成功分家产,就分手,这个脑补的很棒了,就是看一下能不能成功均分呢。

解题思路:求出所有石头的价值总和,然后对所有石头进行多重背包,然后看看是否存在价值和一半的dp值,若有,就是能均分,否则就不能均分 。 

ac代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define maxn 1000005
using namespace std;

int dp[maxn];
int num[10];
int w[maxn];
int main()
{
	int count=0; 
	int cnt;
	while(1)
	{
		count++;
		cnt=0;
		memset(dp,0,sizeof(dp));
		memset(num,0,sizeof(num));
		memset(w,0,sizeof(w));
		int sum=0;
		for(int i=1;i<=6;i++)
		{
			scanf("%d",&num[i]);
			sum+=num[i]*i;
			int k=1;
			int m=num[i];
			while(k<m)
			{
				w[cnt++]=k*i;
				m-=k;
				k*=2;
			}
			w[cnt++]=m*i;
		}
		if(sum==0)
			break;
		if(sum%2)
			printf("Collection #%d:\nCan't be divided.\n",count);
		else
		{
			sum/=2;
			for(int i=0;i<cnt;i++)
				for(int j=sum;j>=w[i];j--)
				{
					dp[j]=max(dp[j],dp[j-w[i]]+w[i]);
				}
			if(dp[sum]==sum)
				printf("Collection #%d:\nCan be divided.\n",count);
			else
				printf("Collection #%d:\nCan't be divided.\n",count);
		}
		printf("\n");
	}
} 

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/81747286