hdu 1455 Sticks

    xiaoxiao2022-06-29  68

    http://acm.hdu.edu.cn/showproblem.php?pid=1455

     

    http://www.acmerblog.com/hdu-1455-Sticks-1979.html

     

    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<cstring> #include<algorithm> using namespace std; struct stick{ int length; //长度 int mark; //标记是否被使用过 }; stick sticks[64]; int n,num,sum; int cmp(const stick &s1,const stick &s2){ return s1.length>s2.length; } //len当前的长度,count当前长度为len的木棒的根数 int dfs(int len,int l,int count,int pos){ if(len==sum)return 1;//如果当期的长度就是所有木棒的总长 if(count==num)return 1; for(int i=pos;i<n;i++){ if(sticks[i].mark)continue; //没有被标记过的 if(len==(sticks[i].length+l)){ sticks[i].mark=1; if(dfs(len,0,count+1,0))//长度相等时,还是要从第一根开始搜 return 1; sticks[i].mark=0; return 0; }else if(len>(sticks[i].length+l)){ sticks[i].mark=1; l+=sticks[i].length; if(dfs(len,l,count,i+1)) return 1; l-=sticks[i].length;//如果不成功,就要恢复 sticks[i].mark=0; if(l==0)return 0;//当前搜索,如果前面的l为0,但第一根没有用上,那么这根木棒就要舍弃 while(sticks[i].length==sticks[i+1].length)i++;//这根不成功的话,则相连的长度相同的不要 } } return 0; } int main(){ while(scanf("%d",&n)!=EOF){ if(n==0)break; sum=0; for(int i=0;i<n;i++){ scanf("%d",&sticks[i].length); sticks[i].mark=0; sum+=sticks[i].length; } sort(sticks,sticks+n,cmp); for(int len=sticks[0].length;len<=sum;len++){ if(sum%len)continue; num=sum/len; //原来长度为len的木棒的根数 if(dfs(len,0,0,0)){ printf("%d\n",len); break; } } } return 0; }

     

    转载请注明原文地址: https://ju.6miu.com/read-1125403.html

    最新回复(0)