POJ1011 Sticks
Sticks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 72127 | Accepted: 15839 |
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 should 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
Central Europe 1995
//搜索+剪枝
//搜索+剪枝
1 #include <cstdlib> 2 #include <iostream> 3 #include <cstdio> 4 #include <algorithm> 5 #include <string.h> 6 #include <cmath> 7 using namespace std; 8 9 int data[66]; 10 bool tag[65]; 11 int n; 12 bool dfs(int length,int left_length,int left_sum) 13 { 14 if((left_sum==0)&&(left_length==0)) 15 return true; 16 if(left_length==0) 17 left_length=length; 18 19 if(left_length>left_sum) 20 return false; 21 22 23 int i,j,k; 24 for(i=n;i>=1;i--) 25 { 26 if(tag[i]) 27 continue; 28 29 30 if(left_length<data[i]) 31 continue; 32 33 34 if((i!=n)&&(data[i]==data[i+1])&&!tag[i+1]) 35 continue; 36 37 38 tag[i]=true; 39 40 41 42 if(dfs(length,left_length-data[i],left_sum-data[i])) 43 return true; 44 tag[i]=false; 45 46 if(data[i]==left_length||left_length==length) 47 return false; 48 } 49 return false; 50 } 51 52 53 54 int main(int argc, char *argv[]) 55 {//freopen("C:/Users/shp/Desktop/in.txt","r",stdin); 56 //freopen("C:/Users/shp/Desktop/out.txt","w",stdout); 57 58 int i,j,k; 59 int sum=0; 60 while(scanf("%d",&n)!=EOF) 61 {if(n==0)break; 62 sum=0; 63 int maxlength=0; 64 for(i=1;i<=n;i++) 65 {scanf("%d",&data[i]);sum+=data[i]; 66 if(data[i]>maxlength) 67 maxlength=data[i]; 68 } 69 memset(tag,false,sizeof(tag)); 70 sort(data+1,data+n+1); 71 for(i=maxlength;i<=sum;i++) 72 { 73 if(sum%i!=0) 74 continue; 75 76 if(dfs(i,i,sum)) 77 {cout<<i<<endl;break;} 78 } 79 80 81 } 82 83 84 85 86 87 system("PAUSE"); 88 return EXIT_SUCCESS; 89 }