poj 1011 sticks

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
这个题不看题解,真的想不出来,因为肯定是dfs,但是情况非常多,所以剪枝很烦,我们先排序之后,肯定是从maxlen开始遍历;
然后就到了dfs的重点
bool dfs(int num,int mubiao,int nowlen,int start) num表示现在dfs到哪一个,目标就是我们要找的数,nowlen表示现在棍子的长,start表示开始在哪
也就是,从s开始往后,能不能利用现在的nowlen,找到mubiao,当num结束时候结束,这个特点有一点“分解子问题”的特质
后面的dfs中“当正好找到一组之后”,nowlen变成零,又从头开始找;
真的,这个递归条件也是真的绕

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
int n;
int a[68];
int vis[108];
bool dfs(int num,int mubiao,int nowlen,int start)
{
    if(num==n)
    return true;
    int sample=-1;
    for(int i=start;i<n;i++)
    {
        if(vis[i]==true||sample==a[i])
        {
            continue;
        }
        vis[i]=true;
        if(nowlen+a[i]<mubiao)
        {
            if(dfs(num+1,mubiao,nowlen+a[i],i))
            return true;
            else
            sample=a[i];
        }
        else if(nowlen+a[i]==mubiao)
        {
            if(dfs(num+1,mubiao,0,0))
            {
                return true;
            }
            else
            {
                sample=a[i];
            }
        }
        vis[i]=false;
        if(nowlen==0)
        break;
    }
    return false;
}    

int main()
{   
    while(true)
    {
        cin>>n;
        if(n==0)
        break;
        int sum=0;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            vis[i]=false;
            sum+=a[i];
        }
        sort(a,a+n,greater<int>());
        int maxlen=a[0];
        int minlen=a[n-1];
        int flag=0;
        int len;
        for(int i=maxlen;i<=sum-maxlen;i++)
        {
            if(sum%i==0)
            {
                if(dfs(0,i,0,0))
                {
                    flag=1;
                    len=i;
                    break;
                }
            }
       }
       if(flag==0)
       printf("%d\n",sum);
       else
       printf("%d\n",len);
    }
}

 


posted @ 2019-07-06 21:25  coolwx  阅读(167)  评论(0编辑  收藏  举报