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
帮助乔治计算木棒的可能最小长度
原本的木棍长度肯定比最长的小木棍长,小于小木棍总和
越长的小木棍灵活度越差,所以木棍数要从大到小排序
其次是剪枝
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=1e6+10;
int a[N],vis[N];
int num,k,n;
bool cmp(int a,int b)
{
return a>b;
}
int dfs(int t,int l,int j)
{
if(t>num)
return 1; //停止条件 所有木棒都已经拼好
if(l==k)
return dfs(t+1,0,1); //搜下一根
for(int s=j; s<=n; s++)
{
if(!vis[s]&&l+a[s]<=k)
{
vis[s]=1;
if(dfs(t,l+a[s],s+1))
return 1;
vis[s]=0;
if(l==0||l+a[s]==k) //如果剩下的木棍组成不了或找不到开始的木棍
return 0;
}
}
return 0;
}
int main()
{
while( ~scanf("%d",&n)&&n)
{
int sum=0;
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a+1,a+1+n,cmp);
for( k=a[1]; k<=sum; k++)
{
if(!(sum%k))
{
memset(vis,0,sizeof(vis));
num=sum/k;
if(dfs(1,0,1)) //木棍数 长度 下标
break;
}
}
printf("%d\n",k);
}
return 0;
}