HUD1455:Sticks

Sticks

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8839    Accepted Submission(s): 2623


Problem 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 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
思路:做本题之前先做HDU1518,dfs+剪枝。见代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN=65;
int n;
int sticks[MAXN];
int sum,l;
int vis[MAXN];
bool comp(int a,int b)
{
    return a > b;
}
bool dfs(int dep,int len,int start)//dep:搜索深度,len:sticks连接的长度,start:当前搜索的木棒
{
    if(dep==n)
    {
        if(len==0)
            return true;
        else
            return false;
    }
    for(int i=start;i<n;i++)
    {
        if(!vis[i]&&len+sticks[i]<=l)
        {
            vis[i]=1;
            if(len+sticks[i]<l)
            {
                if(dfs(dep+1,len+sticks[i],i+1))
                    return true;
            }
            else
            {
                if(dfs(dep+1,0,0))
                    return true;
            }
            vis[i]=0;
            if(len==0)    return false;//如果sticks[i]作为木棒的头却没有匹配成功的话,
                                    //说明sticks[i]不能与其他stick连接,换l从新搜
            while(sticks[i+1]==sticks[i])    i++;//若本次sticks不可以,则与它等长的也不可以
        }
    }
    return false;
}
int main()
{
    while(scanf("%d",&n)!=EOF&&n!=0)
    {
        sum=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&sticks[i]);
            sum+=sticks[i];
        }
        sort(sticks,sticks+n,comp);//必须由大到小排序
        for(l=sticks[0];l<=sum;l++)
        {
            if((sum%l)!=0)    continue;//源sticks是等长的
            memset(vis,0,sizeof(vis));
            if(dfs(0,0,0))
            {
                printf("%d
",l);
                break;
            }                
        }
    }
    return 0;
}
 
原文地址:https://www.cnblogs.com/program-ccc/p/5626994.html