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
题意: 现在有短枝参差不齐若干个,不知原长,不知原数量,求最短的原短枝长度(原短枝长度均相同)
思路: 搜索,将所有短枝从大到小排序求出MAX,则能出现的原短枝len必是处在(MAX,sum)之间,然后从大到小枚举短枝,搜索其与剩下所有的短枝匹配,若出现now_len==len的len,并且能让搜出的匹配数u=n时,则输出当前len
剪枝:剪除相邻长度相同且不能与前一len匹配的短枝,例如10,7,7,7,7 ,7,6,5。由于10与7匹配后不能满足now_len==len,则将后面所有的相同的短枝跳过搜索
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
int n,flag;
int a[70];
bool vis[70];
int cmp(int aa,int bb)
{
return aa>bb;
}
//s是已经用掉的短枝数,u表示当前所在短枝的下标
int len;
void dfs(int s,int now_len,int u)
{
if(flag) return;
if(now_len==0)
{
int k=0;
while(vis[k]) k++;
vis[k]=1;
dfs(s+1,a[k],k+1);
vis[k]=0;
return;
}
if(now_len==len)
{
if(s==n)
{
flag=1;
return;
}
else dfs(s,0,0);
return;
}
for(int i=u;i<n;i++)
{
if(!vis[i]&&now_len+a[i]<=len)
{
if(!vis[i-1]&&a[i]==a[i-1]) continue;//剪枝
vis[i]=1;
dfs(s+1,now_len+a[i],i+1);
vis[i]=0;
}
}
return;
}
int main()
{
while(cin>>n&&n)
{
int sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n,cmp);
flag=0;
//原短枝必在[a[0],sum)之间
for(len=a[0];len<sum;len++)
{
if(sum%len==0)//枚举能整除的len
{
memset(vis,0,sizeof(vis));
dfs(0,0,0);
if(flag) break;
}
}
cout<<len<<endl;
}
return 0;
}