题目:POJ 1101 Sticks(DFS+剪枝)

网友投稿 755 2022-11-26

题目:POJ 1101 Sticks(DFS+剪枝)

题目:POJ 1101 Sticks(DFS+剪枝)

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 should contains the smallest possible length of original sticks, one per line.

#include #include #include using namespace std;int n, a[100], mark[100], mlen;int cmp(int a, int b){ return a>b;}int dfs(int N, int now){ if (N==0 && now==0) return 1; if (now==0) now=mlen; for (int i=1; i<=n; i++){ if (!mark[i] && a[i]<=now){ if (i>1){ if (!mark[i-1] && a[i-1]==a[i]) continue;//上一个相同的棍子没通过,这个也不通过 } mark[i]=1; if (dfs(N-1, now-a[i])){ return 1; }else{ mark[i]=0; if (a[0]==now || now==mlen) return 0; } } } return 0;}int main(){ while (scanf("%d", &n)!=EOF && n){ int i, j, sum; sum=0; for (int i=1; i<=n; i++){ scanf("%d", &a[i]); sum+=a[i]; } sort(a+1, a+n+1, cmp);//由大到小排序 for (i=a[1]; i<=sum/2; i++){//最少两段 if (sum%i==0){//被整除说明可以组成长度为i的x个木棒 for (j=1; j<=n; j++) mark[j]=0;//初始化 mlen=i; if (dfs(n, mlen)){ printf("%d\n", mlen); break; } } } if (i>sum/2) printf("%d\n", sum); } return 0;}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:题目:Yuhao and a Parenthesis(思维)
下一篇:树、二叉树、堆
相关文章

 发表评论

暂时没有评论,来抢沙发吧~