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 file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting. The second line contains the lengths of those parts separated by the space. The last line of the file contains ‘0’.
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
题意:有n段木棒,他们都是由原来等长的木棒随意切割而来的,求原来木棒最短可能是多少。
思路:先求出n段木棒的和,把这些小木棒长度从大到小排序,从第一个开始,一直到sum/2(先假设至少得有两根木棒吧)。原来每根木棒长度相等的,因此咱们假设的木棒的长度是能被能被sum整除的,每次取木棒我们都要记录一下当前位置,下一次取直接从下个位置取即可,直到这跟木棒长度加上后刚好是咱们假设的长度,此时从头开始取。有一个特殊的情况,就是所有咱们for循环的情况都不能成立,那就说明复原后只有一根,它的长度就为是sum,代码如下:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
bool cmp(int x,int y)
{
return x>y;
}
int n,l,flag,s[110],book[110];
void angel(int x,int ans,int len)
{
int i;
if(ans==0&&len==0)
{
flag=1;
return;
}
if(len==0)
{
x=0;
len=l;
}
for(i=x;i<n;i++)
{
if(!book[i]&&s[i]<=len)
{
if(i>0)
{
if(!book[i-1]&&s[i]==s[i-1])
continue;
}
book[i]=1;
angel(i+1,ans-1,len-s[i]);
book[i]=0;
if(flag)
return;
if(s[i]==len||len==l)
return;
}
}
return;
}
int main()
{
int i,j;
while(~scanf("%d",&n)&&n)
{
flag=0;
int sum=0;
for(i=0;i<n;i++)
{
scanf("%d",&s[i]);
sum+=s[i];
}
sort(s,s+n,cmp);
for(l=s[0];l<=sum/2;l++)
{
if(sum%l==0)
{
memset(book,0,sizeof(book));
angel(0,n,l);
if(flag)
break;
}
}
if(!flag)
printf("%d\n",sum);
else
printf("%d\n",l);
}
}