Description
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段木棒的和,并将它从大到小排序,我们可以想一下,最后合成的木棍的长度肯定比分割后的长度长。我们可以从a[0]~sum之间进行而枚举,看这样的长度是否满足。我们此时可以使用深搜的方法,每次我们从枚举的长度len开始进行迭代,到分割的木棍用光后看是否len也为0;
但是我们也需要一点巧妙的剪枝,那就是单独的木棍长度等于枚举的len,同时,如果一段木棍不可以的话其中相同长度的木棍也可以直接省略
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a>b;
}
int n,a[21],book[21];
int dfs(int len,int remain,int num)
{
if(remain==0&&num==0) return 1;
if(remain==0) remain=len;
for(int i=0;i<n;i++)
{
if(book[i]) continue;
if(remain>=a[i])
{
book[i]=1;
if(dfs(len,remain-a[i],num-1)) return 1;
book[i]=0;
if(remain==a[i]||len==remain) break;
while(a[i]==a[i+1]) i++;
}
}
return 0;
}
int main()
{
while(scanf("%d",&n),n)
{
int i,sum=0;
memset(book,0,sizeof(book));
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n,cmp);
for(i=a[0];i<=sum;i++)
{
if(sum%i==0)
{
if(dfs(i,i,n))
break;
}
}
printf("%d\n",i);
}
return 0;
}