Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3582 Accepted Submission(s): 903
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
這是以前做過的題poj(1011),當時從網上看了好久,雖然過了,可是隔了這么久了,發現還是有必要再寫一遍
這次AC的就容易多了,和以前寫的差不多,這次用了一個結構體存儲木棒信息,但是所有的剪枝還是沒有少,這里是剪枝的經典運用,一定要學好了。。。。
干巴爹。。。
#include <iostream> #include <algorithm> using namespace std; //total能組成的木棒的組數,l:組成的木棒的長度 int total,l; //num:輸入的整數,sum:總長度 int num,sum; typedef struct { int length;//木棒的長度 bool mark;//木棒是否被使用過 }Sticks; Sticks sticks[70]; bool cmp(Sticks a,Sticks b) { return a.length>b.length; } //s 已組成的木棒數目,len已經組成的長度,pos搜索的木棒的下標的位置 int dfs(int s,int len,int pos) { if(s==total)return 1; for(int i=pos+1;i<num;i++) { //如果這個木棒已經用過,則繼續下一根 if(sticks[i].mark)continue; if(len+sticks[i].length == l) { sticks[i].mark = true; if(dfs(s+1,0,-1))return true; sticks[i].mark = false; return false; }else if(sticks[i].length+len<l){ sticks[i].mark = true; if(dfs(s,len+sticks[i].length,i)) return true; sticks[i].mark = false; //剪枝:如果當前搜索時,前邊的長度為0,而第一根沒有成功的使用, //說明第一根始終要被廢棄,所以這種組合必定不會成功 //此處的剪枝必須有,因為這里的剪枝會節省很多的無用搜索, //我試了一下,此處剪枝省去就會超時的。。。。 if(len==0)return false; //剪枝:如果當前和上一次搜到的木棒是一樣長的則沒必要再搜一次了 while(sticks[i].length==sticks[i+1].length)i++; } } return false; } int main() { while(cin>>num&&num!=0) { sum = 0;//標記為0 for(int i = 0; i < num; i++) { cin>>sticks[i].length; sum += sticks[i].length; sticks[i].mark = false; } //將木棒按照長度從長到短的順序排序 sort(sticks,sticks+num,cmp); //從木棒的最長的那根開始搜索,因為最小的組合也會大於等於最長的那根 for(l = sticks[0].length; l <= sum; l++) { //剪枝一:如果不能被整除說明不能組成整數根木棒,搜下一個 if(sum%l!=0)continue; total = sum / l;//得到木棒總數目 if(dfs(1,0,-1)) { cout<<l<<endl; break; } } } return 0; }