Poj1014 Dividing

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 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
2
3
1 0 1 2 0 0 
1 0 0 0 1 1
0 0 0 0 0 0

Sample Output

1
2
3
4
5
Collection #1:
Can't be divided.

Collection #2:
Can be divided.

Analysis

此题可背包,可DFS,这里使用DFS做法。

DFS

每次探测六种选择,进行一次选择后数量减一同时递归,若在递归过程中存在一次结果为总价值的一半,则DFS结束,否则不能平分。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;
int num[7];
int Case;
int sum;
int half;
int flag;
void dfs(int value, int pre)
{
if (flag)
return;
if (value == half)
{
flag = true;
return;
}
for (int i = pre; i >= 1; i--)
{
if (num[i])
{
if (value + i <= half)
{
num[i]--;
dfs(value + i, i);
if (flag)
break;
}
}
}
return;
}
int main()
{
Case = 1;
while (cin >> num[1] >> num[2] >> num[3] >> num[4] >> num[5] >> num[6])
{
sum = 0;
for (int i = 1; i <= 6; i++)
{
sum += i * num[i];
}
if (sum == 0)
break;
half = sum / 2;
flag = false;
dfs(0, 6);
if (sum % 2 || !flag)
{
cout << "Collection #" << Case << ":" << endl;
cout << "Can't be divided." << endl << endl;
}
else
{
cout << "Collection #" << Case << ":" << endl;
cout << "Can be divided." << endl << endl;
}
Case++;
}
return 0;
}