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
Java:
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
static int n, sum = 0, t;
static int []mapp = new int [100];
static int []mapp1 = new int [100];
static int []vis = new int [100];
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
while(cin.hasNext())
{
n = cin.nextInt();
if(n==0)
break;
for(int i=1; i<=n; i++)
{
mapp[i] = cin.nextInt();
sum += mapp[i];
}
Arrays.sort(mapp, 1, n+1);
for(int i=1; i<=n; i++)
{
mapp1[n-i+1] = mapp[i];
}
for(int i=1; i<=n; i++)
{
mapp[i] = mapp1[i];
}
int len;
//原木棒的长度应该为 比 所有被折断木棒中最长的长,比所有木棒总长的一半短;
for(len=mapp[1]; len<=sum/2; len++)
{
if(sum%len!=0)
continue;
Arrays.fill(vis, 0);
t = len;//标记当前所尝试的木棒;
if(dfs(len, n)==1)//len为还需要的长度, n为还有n根可以选择;
{
System.out.println(len);
break;
}
}
//如果 被折断木棒最长的 比所有木棒总长的一半长, 说明其 原木棒的最小长度为所有木棒之和;
if(len>sum/2)
System.out.println(sum);
}
}
static int dfs(int len, int m)
{
if(m==0&&len==0)
return 1;
//说明 这一根已经满足要求,但木棒还有剩余,要开始连接下一根,len又开始等于原木棒长度;
if(m!=0&&len==0)
len = t;
for(int i=1; i<=n; i++)
{
if(vis[i]==0&&mapp[i]<=len)
{
vis[i] = 1;
if(dfs(len-mapp[i], m-1)==1);//在还需要的长度中减去这根木棒,剩余木棒数 也减去1;
return 1;
else
{
vis[i] = 0;
if(len==t||len==mapp[i])
return 0;
}
}
}
return 0;
}
}