Description
George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.
Input
The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.
Output
The output should contains the smallest possible length of original sticks, one per line.
Sample Input
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
Sample Output
6 5
#include <iostream>
#include <algorithm>
#include <bitset>
using namespace std;
int N = 64, L = 0;
bitset<64> used = 0;
int sticks[64] = {0};
bool dfs(int start, int needed)
{
if (needed == 0) {
if (used.count() == N)
return true;
start = 0;
needed = L;
}
for (; start < N; ++start) {
if (used.test(start) || sticks[start] > needed)
continue;
used.set(start);
if (dfs(start+1, needed-sticks[start])) return true;
used.reset(start);
//减枝, 若当前不成功,那么即使以后找到长度和等于needed的小棒,也肯定不会成功
if (needed == sticks[start]) break;
//减枝, 第一个放入的start处小棒是能放入的最长小棒,且必定要放入,
//显然若此时失败,之后的就不用搜索了
if (needed == L) break;
while (start+1 < N && sticks[start+1] == sticks[start])
start++;
}
return false;
}
int main()
{
while (cin >> N) {
if (N == 0) break;
for (int i = 0; i < N; ++i)
cin >> sticks[i];
std::sort(sticks, sticks+N, std::greater<int>());
int sum = 0;
for (int i = 0; i < N; ++i)
sum += sticks[i];
for (L = sticks[0]; L <= sum; ++L) {
if (sum % L == 0) {
used.reset();
if (dfs(0, L)) {
cout << L <<endl;
break;
}
}
}
}
return 0;
}
测试数据:
9
5 2 1 5 2 1 5 2 1
9
15 3 2 11 4 1 8 8 8
6
6 2 2 4 8 8
5
1 1 1 1 1
2
1 1
4
2 2 9 9
3
1 2 3
64
40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 43 42 42 41 10 4 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40
7
49 48 47 46 45 44 43
7
3 4 5 5 5 5 13
7
2 7 7 7 7 10 20
6
1 2 3 11 11 20
7
63 2 44 12 60 35 60
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
64
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 33 33 31 31
64
40 40 30 35 35 26 15 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 43 42 42 41 10 4 40 40 40 40 40 40 40 40 40 40 40 40 40 40 25 39 46 40 10 4 40 40 37 18 17 16 15 40 40 40 40 40 40 40 40
45
15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8
0
输出结果:
6
20
10
1
1
11
3
1251
322
20
30
24
276
6
5
64
454
20