您的位置:首页 > 其它

HDU1059 Dividing(母函数,有限制)

2018-02-01 16:10 447 查看

Problem Description

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 describes one collection of marbles to be

divided. The lines consist of six non-negative integers n1, n2, …,

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 colletcion, 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.


思路

有两个人找到了一个宝藏库,在他们面前有6堆宝藏,单个价值分别是
1,2,3,4,5,6
,题目每一行给出六个数代表这6种宝藏的数量,每个宝藏不可分割。问最后的总价值能否两个人平分。

利用母函数,其中v[]数组的值就是从1~6代表这6种宝藏的价值,num[]数组代表数量,最后只需要判断
n/2
的系数是否存在就行。

在求数量的时候要对30取模,不取模会超时(不过真的不知道为什么这样啊)

同时也可以用多重背包解决这个题: HDU1059 Dividing(多重背包,二进制优化,模板题)

代码

#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
#define inf 1000000
#define mem(a,b) memset(a,b,sizeof(a))
const int N=8000+7;

int c1
,c2
,num
;
int v[10]= {0,1,2,3,4,5,6};
int main()
{
int q=1;
while(1)
{
int flag=0,n=0;;
for(int i=1; i<=6; i++)
{
scanf("%d",&num[i]);
num[i]%=30;
if(num[i]==0)
flag++;
else
n+=num[i]*i;
}
if(flag==6) break;
printf("Collection #%d:\n",q++);
if(n&1)
{
puts("Can't be divided.\n");
continue;
}
mem(c1,0);
c1[0]=1;
for(int i=1; i<=6; i++)
{
mem(c2,0);
for(int j=0; j<=num[i]; j++)
for(int k=0; k+j*v[i]<=n; k++)
c2[k+j*v[i]]+=c1[k];
memcpy(c1,c2,sizeof(c2));
}
if(c1[n/2])
puts("Can be divided.");
else
puts("Can't be divided.");
puts("");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: