HDU 1455 Sticks

来源:互联网 发布:淘宝卖什么利润大 编辑:程序博客网 时间:2024/06/06 00:47
 

Sticks

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


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
 

Source
ACM暑期集训队练习赛(七)
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  1258 1312 1067 1010 1016 

题意:找出满足能将n根筷子分成m个筷子的最小长度
自己时候一直TLE,后来去看大神的博客才明白:http://blog.csdn.net/lttree/article/details/23103573,剪枝真的重要,剪枝思路如下
剪枝一:
如果搜索失败回溯后的长度等于当前的长度,直接返回,例如res回溯后等于3,当前搜索的长度恰好为3,说明一定不满足,直接返回
剪枝
如果搜索失败后回溯的长度res和目标长度maxx相等,即有一个不满足,后面的就没有必要继续去搜索了,这个剪枝很重要
剪枝三:
如果搜索当前搜索的长度不满足,那么与之相等的长度也没有必要去访问

#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<algorithm>using namespace std;#define for1(i,a) for(int (i)=1;(i)<=(a);(i)++)#define for0(i,a) for(int (i)=0;(i)<(a);(i)++)#define mem(i,a) memset(i,a,sizeof i)#define sf scanf#define pf printf#define _f first#define _s secondbool vis[101];int m,i,j,tag,Maxx,sum,a[101];bool cmp(int x,int y){    return x>y;}void dfs(int res,int n,int h){    if(tag==1)return;    if(n==m)    {        tag=1;        return;    }    if(res==0&&n<m)//如果res=0,但未搜索完将res赋值为maxx继续搜索        dfs(Maxx,n,0);    for(int i=h;i<m;++i)    {        if(!tag&&!vis[i]&&a[i]<=res)        {            vis[i]=1;//第i个筷子已访问            dfs(res-a[i],n+1,h);            vis[i]=0;            if(res==a[i])return;第一条剪枝            if(res==Maxx)return;//第二条剪枝(核心)            while(a[i]==a[i+1])++i;//第三条剪枝        }    }}int main(){    while(sf("%d",&m),m)    {        sum=0,tag=0;        for0(i,m)        {            sf("%d",&a[i]);            sum+=a[i];        }        sort(a,a+m,cmp);        Maxx=a[0];        if(Maxx>sum-Maxx)//如果最大的数大于总长度减去最大长度,说明满足条件的最小长度一定是总长度        {            pf("%d\n",sum);            continue;        }        while(!tag)        {            while(sum%Maxx)//最后得到的长度一定满足sum%maxx==0            {                Maxx++;            }            mem(vis,0);            dfs(Maxx,0,0);            if(tag)                break;            ++Maxx;        }        printf("%d\n",Maxx);    }    return 0;}

原创粉丝点击