Poj 1011 Sticks - dblank

# Poj 1011 Sticks

<p class="pst">Description</p>

<div class="ptx" lang="en-US">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.</div>
<p class="pst">Input</p>

<div class="ptx" lang="en-US">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.</div>
<p class="pst">Output</p>

<div class="ptx" lang="en-US">The output should contains the smallest possible length of original sticks, one per line.</div>
<p class="pst">Sample Input</p>

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4

0


<p class="pst">Sample Output</p>

6
5

<p class="pst">Source</p>
<p class="pst">题意:给你一些长度的木棍，问你能够拼成相同长度的木棍的最小长度。</p>
<p class="pst">思路:直接dfs的话是会超时的，要加很多剪枝:</p>
<p class="pst">①在搜索的过程中，如果某一长度的木棍添加失败，则不再该位置尝试这一长度的木棍。</p>
<p class="pst">②搜索的过程中，如果搜索该位置失败，并且这是添加的第一根或者是最后一根，则不再搜索该节。</p>
<p class="pst">③搜索的过程中，保证每次搜索添加的是从大到小的顺序，可以避免很多重复的分支。</p>

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstring>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cmath>
using namespace std;
const double eps = 1e-10;
const int inf = 0x3f3f3f3f, N = 5000 + 10, Mod = 1000000000;
typedef long long ll;
int n, a[N], vis[N], L, last;
int dfs(int N, int M)
{
if(N == 0 && M == 0)
return 1;
if(M == 0)
M = L;
int now = 0;
if(M != L)
now = last+1;
for(int i = now; i<n; i++)
{
if(!vis[i] && a[i] <= M)
{
if(i>0 && !vis[i-1] && a[i-1] == a[i])
continue;
vis[i] = 1, last = i;
if(dfs(N-1, M - a[i]))
return 1;
else
{
vis[i] = 0;
if(M == L || M == a[i])
return 0;
}
}
}
return 0;
}
int main()
{
while(cin>>n && n)
{
int sum = 0, yes = 0;
for(int i = 0; i<n; i++)
scanf("%d", &a[i]), sum += a[i];
sort(a, a+n, greater<int>());
for(int i = a[0]; i<=sum/2; i++)
{
memset(vis, 0, sizeof(vis));
L = i;
if(sum % i)
continue;
if(dfs(n, i))
{
yes = 1;
printf("%dn", i);
break;
}
}
if(!yes)
printf("%dn", sum);
}
return 0;
}