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

 

【题意】给出n个长度的短棒,是由原来等长的小棒任意剪切而来,问原来的小棒最短的长度是多少

【思路】用dfs搜索,重点是其中的几个剪枝,不减的话会超时。

 

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int N=105;
int n;
int d,num;
int val[N];
int vis[10005];
bool flag;
int cmp(int x,int y)
{
    return x>y;
}
void dfs(int k,int len,int num1)
{
    if(flag==1) return ;
    if(len==d)
    {
        dfs(0,0,num1+1);
        if(flag==1) return ;
    }
    if(num1==num)
    {
        flag=1;
        return ;
    }
    for(int i=k;i<=n;i++)
    {
        if(!vis[i]&&len+val[i]<=d)
        {
            vis[i]=1;
            dfs(i+1,len+val[i],num1);
            vis[i]=0;
            if(len==0) return ;

//如果当前搜索时,前面的长度为0,而第一根没有使用,说明第一根始终要废弃,这种组合必然不会成功

            if(len+val[i]==d) return ;
            if(val[i]==val[i+1]) i++;

//如果当前和上一次搜到的木棒一样长,就没必要再搜了


        }
    }

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

    return 0;
}