UESTC Training for Search Algorithm——L

来源:互联网 发布:土豪微信提现ae源码 编辑:程序博客网 时间:2024/06/04 17:53

Sticks

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

Central Europe 1995

 

 

/*算法思想:  我用DFS做的,先将所有的木棍从大到小排序,然后从最大的木棍开始枚举木棍能  拼接的长度len,要是能拼接,退出循环,输出结果  剪枝1:要是这跟木棍不能用来拼接,那么其他的和他长度相等的木棍也不能拼接  剪枝2:不能找到一根长度为len的木棍,直接退出搜索,以后也不能找到了*//*CODE*/#include<iostream>#include<cstring>#include<cmath>#include<cstdio>#include<algorithm>#define N 100using namespace std;int a[N],sum,n,len;bool fg[80];bool cmp(int a,int b){    return a>b;}bool dfs(int v,int left,int tot)  //DFS,当前用到第v根木棍了,还剩下len凑够一根长度为len的木棍,总的木棍长度还剩tot{    if(tot==len) return true;  //如果总的木棍长度还剩tot,一定能够凑够    for(int i=v;i<n;i++)    if(!fg[i] && a[i]<=left)  //找一根能够用来拼凑的木棍    {        fg[i]=true;        if(a[i]==left)        {            if(dfs(0,len,tot-a[i])) return true;  //找新的一根长度为len的木棍        }        else if(dfs(i+1,left-a[i],tot-a[i])) return true;        fg[i]=false;        if(a[i]==left) return false;  //不能找到一根新的长度为len的木棍,肯定不能找到了,返回false        if(tot==sum) return false;  //用于第一次DFS,要是不能找到,返回false        if(left==len) return false;  //不能找到一根长度为len的木棍,返回false        while(a[i]==a[i+1]) i++;  //相同的木棍,上一个满足条件找了不能找到,这一个也一样的不能    }    return false;}int main(){    while(scanf("%d",&n),n!=0)    {        sum=0;        for(int i=0;i<n;i++)        {            scanf("%d",&a[i]);            sum+=a[i];        }        sort(a,a+n,cmp);        memset(fg,0,sizeof(fg));        for(len=a[0];len<=sum;len++)        {            if(sum%len!=0) continue;            if(dfs(0,len,sum)) { printf("%d\n",len); break; }        }    }    return 0;}


 

原创粉丝点击