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
分析
找到最小的等长原木棍,范围是 木棍中最大的到木棍之和sum。
由于是等长的 ,所以到sum/2还没找到,则原木棍只有一个长为sum。
较小的木棍与其他木棍组合更多,所以从较大的开始搜索,如果找不到,则说明前面的组合不合理,直接break,再从前面找。
对于每个木棍,由于是按顺序搜索的,所以说明含有前面木棍长度都试过了或者用过,因此从这个木棍之后找组合。
回溯是说明这个木棍长度在这个组合中不合理,因此与它等长的也不合理,应换一个长度。
找到一个合法的原木棍长度,则它就是最小的,用一个标记已找到,直接返回。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,fg,l,a[110],v[110];
bool cmp(int x,int y)
{
return x>y;
}
void dfs(int num,int sum,int h)
{
if(fg) return;
if(num==n)
{
if(sum==0)
fg=1;
return;
}
if(sum==0)
{
for(int i=0; i<n; i++)
{
if(!v[i])
{
v[i]=1;
dfs(num+1,l-a[i],i);
v[i]=0;
break;
}
}
}
else
{
for(int i=h+1; i<n; i++)
{
if(!v[i]&&sum>=a[i])
{
v[i]=1;
dfs(num+1,sum-a[i],i);
if(fg) return;
v[i]=0;
while(i+1<n&&a[i]==a[i+1]) i++;
}
}
}
return ;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
fg=0;
int i,sum=0;
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n,cmp);
for(i=a[0]; i<=sum/2; i++)
{
if(sum%i==0)
{
memset(v,0,sizeof(v));
l=i;
dfs(0,0,i);
if(fg) break;
}
}
if(!fg) printf("%d\n",sum);
else printf("%d\n",l);
}
return 0;
}