Sticks
Sticks |
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 zero.
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
George拿了一些相同长度的棍子,然后随意的把这些棍子切成一段一段的棍子(每段长度都不会超过50个单位长)。现在他想要把这些一段一段的棍子拼回原来的样子,但是他忘了他原来带多少根棍子来,并且也忘了原来每根棍子的长度。请帮助他设计一个程式算出这些棍子原来可能的最小长度。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int arry[100],vis[100];
int n,m,judge,len;
bool cmp(int x,int y)
{
return x>y;
}
void dfs(int pos,int num,int lenth)
{
if(judge) return;
if(num==m/len)
{
judge=1;
return;
}
int i,pre=-1;//剪枝条件4,pre记录上一次组合的长度
for(i=pos;i<n;i++)
{
if(vis[i]==0&&arry[i]!=pre)
{
pre=arry[i];
if(lenth+arry[i]<len)
{
vis[i]=1;
dfs(i+1,num,lenth+arry[i]);
vis[i]=0;
if(lenth==0) return;//剪枝条件5
}
else if(lenth+arry[i]==len)
{
vis[i]=1;
dfs(0,num+1,0);
vis[i]=0;
return;
}
}
}
if(judge) return;
}
int main()
{
while(cin>>n&&n)
{
memset(vis,0,sizeof(vis));
m=0,judge=0,len=0;
for(int i=0;i<n;i++)
{
cin>>arry[i];
m=m+arry[i];
if(arry[i]>len) len=arry[i];
}
sort(arry,arry+n,cmp);//剪枝条件3
for(;len<=m;len++)//剪枝条件1
{
if(m%len==0)//剪枝条件2
{
dfs(0,0,0);
if(judge==1) break;
}
}
cout<<len<<endl;
}
return 0;
}