Sticks(递归经典)

 原题  http://poj.org/problem?id=1011

答案(比较全)http://www.cnblogs.com/mycapple/archive/2012/08/14/2638430.html#commentform




Sticks
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 119148   Accepted: 27482

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






#include <iostream>

#include <algorithm>
using namespace std;
int a[100];
bool b[100];//看第i个杆子是否被用过;
int n,sum;

bool cmp(int a,int b){return a>b;}
bool p(int left,int leng,int we)
{
    int i;
    if(left==0&&we==0)return 1;//最后如果数都用完了,并且sum==0,即代表该数是原杆子
    if(left==0)left=leng;//如果left==0;代表一个杆子拼完了,开始新的一根
    for(i=0;i<n;i++)//从a[0]开始拼杆子
    {
        if(a[i]<=left&&!b[i])//被拼的杆子必须没被用过
        {b[i]=1;
        if(p(left-a[i],leng,we-1))
            return 1;
        b[i]=0;
        if(a[i]==left||left==leng)//如果p()返回0,又因为如果a[i]==left或left==leng,即代表left从leng开始,又因为前面返回的0;所以i以后的数都不行,可以return 0
            return 0;
        }
    }
    return 0;
}



int main()
{int i,l;
while(scanf("%d",&n)!=EOF&&n)
{sum=0;
for(i=0;i<n;i++)
{scanf("%d",&a[i]);sum=sum+a[i];b[i]=0;}
sort(a,a+n,cmp);

for(l=a[0];l<=sum;l++){
    if(sum%l==0&&p(l,l,n))//如果l是最小数,那l肯定能被整除
    {
        
        
        printf("%d\n",l);break;
        
    }
}

}
return 0;}

posted @ 2014-07-16 13:35  冷夏的博客园  阅读(342)  评论(0编辑  收藏  举报