hdu 1445 sticks (经典dfs+剪枝)

来源:互联网 发布:量化交易程序员 招聘 编辑:程序博客网 时间:2024/06/05 05:13
 sticks 
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<string.h>#include<algorithm>using namespace std;int n,sum,len;int stick[64];int visit[64];bool cmp(int a,int b){return a>b;}int dfs(int num,int l){int i;if(num==0&&l==0) return 1;if(l==0) l=len;for(i=0;i<n;i++)if(!visit[i]&&stick[i]<=l){if(i>0&&!stick[i-1]&&stick[i]==stick[i-1]) continue;//与前一个相同的搜索visit[i]=1;if(dfs(num-1,l-stick[i])) return 1;else{visit[i]=0;if(stick[i]==l||l==len) return 0;/* BLACKBOOK:Page181 1,为了避免重复搜索,按照木棍的第一段长度递增的顺序搜索每根木棍, 在每根木棍中按照长度递减的顺序考虑每个可能的长度, 2,  如果某长度刚好能够填满一根原始木棍,就没有必要考虑其他木棍了; 如果使用更短的小木棍,即使存在某个也能填满该原始木棍的方法,该方法也一定不会 比用大木棍更有希望获得可行解 (比如a b c d e f,目标长度为a+b,且为失败搜索,则a+b之后即退出,比如b==d+e的话, 将b替换为d+e,若有成功搜索,则肯定有某个和为a,若有,它在a+b搜索之后就应该搜索过了和 [b+e]组合的,所以重复搜索) */  }}return 0;}int main(){int i;while(cin>>n&&n){sum=0;for(i=0;i<n;i++){cin>>stick[i];sum+=stick[i];}sort(stick,stick+n,cmp);//从大到小排序for(i=stick[0];i<=sum;i++)if(sum%i==0){len=i;memset(visit,0,sizeof(visit));if(dfs(n,len)) {cout<<len<<endl;break;}}}return 0;}


0 0
原创粉丝点击