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
题解:注释的很详细了。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
int a[70],b[70];
int n,sum,temp,flag,maxx;
int dfs(int cur,int num)
{
if(num==0 && cur==0)
return 1;
if(cur==0)
cur=temp;
for(int i=0; i<n; i++)
{
if( a[i]>cur || b[i]==1 )
continue;
b[i]=1;
if(dfs(cur-a[i],num-1))//判断能否拼接完成
return 1;
b[i]=0;
if(a[i]==cur||cur==temp) /*a[i]=cur 或 cur=temp时本来表示即将拼成一根棒,或刚进行新一轮拼接
(即if中判断的是主问题性质完全相同的子问题)但经过上面的if判断,子问题不能
完成所有任务,那么整体不可能完成任务,不再考虑,搜索失败(剪枝)*/
break;
while(a[i]==a[i+1])// a[i] 无法使用,故与 a[i] 相等的都无法使用;
i++;
}
return 0;
}
bool cmp(int x,int y)
{
return x>y;
}
int main()
{
while(cin>>n && n)
{
//memset(b,0,sizeof(b));
sum=0;
maxx=0;
for(int i=0; i<n; i++)
{
cin>>a[i];
sum+=a[i];
if(a[i]>maxx)
maxx=a[i];
}
sort(a,a+n,cmp);
for(int i=n; i>=1; i--)//最终合成 i 段 木棍;
{
if(sum%i==0 && sum/i>=maxx)
{
temp=sum/i;//每段长度为temp
flag=i;
memset(b,0,sizeof(b));
if(dfs(temp,n))
break;
}
}
cout<<temp<<endl;
}
}