首页 > 代码库 > hdu1455 Sticks 深搜 强剪枝

hdu1455 Sticks 深搜 强剪枝

Sticks

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


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题意:给多组数据,每组数据代表一些小木棍,能否将它们全部用完组成(尽量)多个相同长度的长棍,并输出长棍的长度代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int ss,t,d,m;
int q[99];
int vis[99];
int cmp(int a,int b)
{
    return a>b;
}
void dfs(int k,int length,int num)    //  k是搜到第几根棍子   length是当前棍子长度  num是已拼好的棍子数
{
    if(t==1)
        return;
    if(num==ss)
    {
        t=1;
        return ;
    }
    if(length==d)
    {
        dfs(0,0,num+1);   //拼好的棍子加1
         if(t==1)
            return;
    }
    for(int i=k; i<m; i++)
    {
        if(vis[i]==0&&length+q[i]<=d)    //剪枝2
        {
            vis[i]=1;
            dfs(i+1,length+q[i],num);
            vis[i]=0;
            if(d-length==q[i])            //剪枝3 满足当前拼好的长棍 但不满足之后的长棍 也不用继续搜了
                return;
            if(length==0)                //剪枝4 最重要的 不写 直接TLE  当递归回来前面长棍子没用到的话 之后也就用不到了 
                return;
            if(q[i]==q[i+1])               //剪枝5 相同的棍子 都拼不好 直接跳过
            i++;
        }
    }
}
int main()
{
    int i;
    int s;
    int max1;
    while(~scanf("%d",&m))
    {

        if(m==0)
            break;
        s=0;
        t=0;
        for(i=0; i<m; i++)
        {
            scanf("%d",&q[i]);
            s=s+q[i];
        }
        sort(q,q+m,cmp);        //按从大到小排序
        max1=q[0];              
        for(i=max1; i<s; i++)    //应从最长那根的长度开始枚举 否则WA
        {
            if(s%i==0)             //剪枝1:木棍要全部用完 而且多个长木棍要长度相同
            {
                memset(vis,0,sizeof(vis));
                ss=s/i;
                d=i;
                dfs(0,0,0);
            }
            if(t==1)
                break;
        }
        printf("%d\n",i);
    }
    return 0;
}