Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 150282 | Accepted: 35746 |
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
翻译:
乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍的长度都不超过50个长度单位。然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。请你设计一个程序,帮助乔治计算木棒的可能最小长度。每一节木棍的长度都用大于零的整数表示。
输入包含多组数据,每组数据包括两行。第一行是一个不超过64的整数,表示砍断之后共有多少节木棍。第二行是截断以后,所得到的各节木棍的长度。在最后一组数据之后,是一个零。
为每组数据,分别输出原始木棒的可能最小长度,每组数据占一行。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int stick[100], n; bool used[100]; int cmp(int x,int y){ return x>y; } bool dfs(int unused,int left,int len){ if(unused==0&&left== 0) return true; if(left==0) left=len; for(int i=0;i<n;i++){ if(!used[i]&&stick[i]<=left){ used[i]=true; if(dfs(unused-1,left-stick[i],len)) return true; used[i]=false; if(stick[i]==left||left==len) break; } } return false; } int main(){ int sum; while(scanf("%d",&n)!=EOF&&n){ sum=0; for(int i=0;i<n;++i){ scanf("%d",&stick[i]); used[i]=false; sum+=stick[i]; } sort(stick,stick+n,cmp); for(int i=stick[0];i<=sum;++i) if(sum%i==0) if(dfs(n,0,i)){ printf("%d\n", i); break; } } return 0; }