hdu 1455 Sticks

来源:互联网 发布:无敌淘宝网小说免费 编辑:程序博客网 时间:2024/05/17 08:59

Sticks

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


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
95 2 1 5 2 1 5 2 141 2 3 40
 

Sample Output
65
经典搜索题
题意,给出几段若干长度的木棍,木棍是由原先等长的若干条木棍截成的,求这些等长的木棍的最小值。
思路:dfs+剪枝
AC代码:
#include <iostream>#include <algorithm>#include <cstring>using namespace std;int cmp(int a,int b){    return a>b;}int s[70],n,sum,amount,len;        //sum表示木棍的总长度,amount表示等长的木棍的条数,len表示等长的木棍的长度bool v[70];bool dfs(int num,int cur,int left)  //num表示已组成的新木棍数目,cur表示搜索到的下标{    //left表示组成新木棍还需要的长度    if(num==amount) return true;   //如果已经组成足够的新木棍数量,则返回    for(int i=cur+1; i<n; i++)    {        if(v[i]) continue;        if(s[i]==left)        {            v[i]=true;            if(dfs(num+1,-1,len))   //成功组成一条新木棍,则重新开始搜索                return true;            v[i]=false;        }        else if(s[i]<left)        {            v[i]=true;            if(dfs(num,i,left-s[i]))    //未组成一条新木棍,继续搜索                return true;            v[i]=false;        }        if(left==len) return false;   //重要剪枝,若这条木棍未被使用,则往后也不会使用它,这个新长度直接舍弃        while(s[i]==s[i+1]) i++;    //剪枝,如果当前和上一次搜到的木棍是一样长的则没必要再搜一次了    }    return false;}int main(){    while(cin>>n,n)    {        sum=0;        for(int i=0; i<n; i++)        {            cin>>s[i];            sum+=s[i];        }        sort(s,s+n,cmp);        memset(v,false,sizeof(v));        for(len=s[0]; len<=sum; len++)   //注意有可能原先只有一条木棍        {            if(sum%len>0) continue;     //若总长度除以等长的木棍的长度有余数,则不可能满足这个长度            amount=sum/len;            if(dfs(1,-1,len))            {                cout<<len<<endl;                break;            }        }    }    return 0;}



原创粉丝点击