题干:

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 file 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

解题报告:

     这题显然是需要优雅的剪枝的。去掉剪枝1会T,去掉剪枝2会280ms。这份代码是参考的网络,二分查找位置。其实这也可以优化一下,让我们凑每一根的时候都是从上一根+1的地方开始选,然后凑新的一根的时候,从头开始查找第一个vis不等于1的木棒,继续递归就行了。这种方法就跟【HDU - 1518】Square 的处理方法其实就差不多了。

 

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAX=10010;
int a[MAX],n;
bool vis[MAX];
int sum;
int div(int x) {
int l=1,r=n;
int mid = (l+r)/2;
while(l<r) {
mid=(l+r)/2;
if(a[mid]>x) l=mid+1;
else r=mid;
}
return l;
}
bool cmp(const int & a,const int & b) {
return a>b;
}

bool dfs(int cnt,int len,int d) {
if(cnt==sum/len) return 1;
int pos = lower_bound(a+1,a+n+1,len-d,cmp) - a;
for(int i=pos; i<=n; i++) {
if(vis[i]) continue;
if(d+a[i]<len) {
vis[i]=1;
if(dfs(cnt,len,d+a[i])) return 1;
vis[i]=0;
if(d==0) return 0;//剪枝1
}
else if(d+a[i]==len) {
vis[i]=1;
if(dfs(cnt+1,len,0)) return 1;
vis[i]=0;
return 0;//剪枝2
}
}
return 0;
}

int main() {
while(~scanf("%d",&n)) {
if(n == 0) break;
memset(vis,0,sizeof(vis));
sum=0;
for(int i=1; i<=n; i++) scanf("%d",a+i),sum+=a[i];
sort(a+1,a+1+n,cmp);
for(int i=a[1]; i<=sum; i++) {
memset(vis,0,sizeof(vis));
if(sum%i!=0) continue;
if(dfs(0,i,0)) {
printf("%d\n",i);
break;
}
}
}
return 0;
}