题目链接:http://poj.org/problem?id=1011

Sticks

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 154895 Accepted: 37034

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

Source

题意概括:

George这家伙一开始把几条长度一样的木棍切成了好多小木棍,后来忘记原来有几条长度一样的木棍了,所以请我们帮帮忙把这些小木棍拼成尽可能长的长度相同的长木棍,输出长度。

解题思路:

先根据小木棍的长度降序排序

枚举木棍长度(可以整除小木棍总长度),DFS凑这些木棍。

剪枝:如果当前这条小木棍不能凑则这一类小木棍都凑不了(这也是要排序的原因)

AC code:

 ///poj 1011 dfs
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#define INF 0x3f3f3f3f
using namespace std; const int MAXN = ;
bool vis[MAXN];
int sticks[MAXN];
int N, sum, len;
bool flag; bool cmp(int x, int y)
{
return x>y;
} void dfs(int dep, int now_len, int st) ///当前已经使用的木条数目,当前木条的长度, 需要处理的木条的下标
{
if(flag) return;
if(now_len == ) ///找木棍头
{
int k = ;
while(vis[k]) k++;
vis[k] = true;
dfs(dep+, sticks[k], k+);
vis[k] = false;
return;
}
if(now_len == len)
{
if(dep == N) flag = true; ///找到满足条件的len了
else dfs(dep, , ); ///没有用完,开始凑新的一根长度为len的木棍
return;
}
for(int i = st; i < N; i++)
{
if(!vis[i] && now_len + sticks[i] <= len)
{
if(!vis[i-] && (sticks[i-] == sticks[i])) continue;
vis[i] = true;
dfs(dep+, now_len+sticks[i], i+);
if(flag) return;
vis[i] = false;
}
}
} void init()
{
memset(vis, , sizeof(vis));
flag = false;
sum = ;
} int main()
{
while(~scanf("%d", &N) && N )
{
init();
for(int i = ; i < N; i++)
{
scanf("%d", &sticks[i]);
sum+=sticks[i];
}
sort(sticks, sticks+N, cmp);
for(len = sticks[]; len < sum; len++)
{
if(sum%len==)
{
dfs(, , );
if(flag) break;
}
}
printf("%d\n", len);
}
return ;
}
04-20 12:26