*HDU1455 DFS剪枝
Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9779 Accepted Submission(s): 2907
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
Source
题意:
若干个棍子被切成若干份小棍子,问怎样将这些小棍子组成一些长度最小的一样长的小棍子。
代码:
1 //DFS+剪枝;先将小木棍从大到小排序,从最长的小木棍开始枚举长度,dfs找到满足的就是最小的。 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 #include<algorithm> 6 using namespace std; 7 int n,num,len,sum; 8 struct stick 9 { 10 int length,mark; 11 }; 12 stick sti[70]; 13 bool cmp(stick x,stick y) 14 { 15 return x.length>y.length; 16 } 17 int dfs(int cnt,int now,int id) //cnt已经组成的小木棍,now正在组的小木棍的长度,id下标. 18 { 19 if(cnt==num) return 1; //找到了 20 for(int i=id;i<n;i++) 21 { 22 if(sti[i].mark) continue; //用过了 23 if(now+sti[i].length==len) 24 { 25 sti[i].mark=1; 26 if(dfs(cnt+1,0,0)) 27 return 1; 28 sti[i].mark=0; 29 return 0; 30 } 31 else if(now+sti[i].length<len) 32 { 33 sti[i].mark=1; 34 if(dfs(cnt,now+sti[i].length,i+1)) 35 return 1; 36 sti[i].mark=0; 37 if(now==0) return 0;//如果这一组当前的第一个没有被标的木棍与其他的任意都不能组成目标长度则这个木棍不能用,这种方案不行 38 while(sti[i].length==sti[i+1].length)//加上这个小木棍不行,那么后面和这个小木棍一样长的就不用考虑了 39 i++; 40 } 41 } 42 return 0; 43 } 44 int main() 45 { 46 while(scanf("%d",&n)&&n) 47 { 48 sum=0; 49 for(int i=0;i<n;i++) 50 { 51 scanf("%d",&sti[i].length); 52 sum+=sti[i].length; 53 sti[i].mark=0; 54 } 55 sort(sti,sti+n,cmp); 56 for(int i=sti[0].length;i<=sum;i++) 57 { 58 if(sum%i) continue;//能整除时才能正好分成num份不剩余。 59 num=sum/i; 60 len=i; 61 if(dfs(0,0,0)) 62 { 63 printf("%d\n",len); 64 break; 65 } 66 } 67 } 68 return 0; 69 }