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
package 递归和回溯;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
class st{
int lenth;
Boolean use;
}
public class Main {
static int sum;
static int n;
static st a[];
static int dfs (int len, int rlen, int num) { //len为每根长度,rlen当前木棒剩余长度,num还剩几根木棒
if(rlen==0&&num==1)
return len;
if(rlen==0) {
rlen=len;
num--;
}
for(int i=0;i<n;i++) {
if(rlen>=a[i].lenth && a[i].use==false) {
a[i].use=true;
if( dfs( len,rlen-a[i].lenth, num) >0 )
return len;
a[i].use=false;
if(!a[i].use) {
for(int j=i+1;j<n&&!a[i].use;j++) {
if(a[i].lenth==a[j].lenth)
i++;
}
}
if(a[i].lenth==rlen||len==rlen)
break;
}
}
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner (System.in);
for(;;) {
n=sc.nextInt();
if(n==0)
break;
a=new st [n+3];
sum=0;
for(int i=0;i<n;i++) {
a[i]=new st();
a[i].lenth=sc.nextInt();
a[i].use=false;
sum+=a[i].lenth;
}
Arrays.sort(a,0,n,new Comparator<st>() {
@Override
public int compare(st o1, st o2) {
// TODO Auto-generated method stub
if(o1.lenth==o2.lenth) return 0;
return o1.lenth>o2.lenth?-1:1;
}
});
// for(int i=0;i<n;i++)
// System.out.println(a[i].lenth);
for(int i=a[0].lenth;i<=sum;i++){
if(sum%i==0){
//System.out.println(i);
for(int j=0;j<n;j++)
a[j].use=false;
int k=dfs(i,i,sum/i);
if(k>0) {
System.out.println(k);
break;
}
}
}
}
}
}