George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Nowhewantstoreturnstickstotheoriginalstate,butheforgothowmanystickshehadoriginally 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个小木块,然后让你拼成若干个同样的高度,看看最小的高度是多少。
这道题涉及的剪枝才是关键,没有剪枝你就等待的是无限超时
1 形成的长度之和肯定能整除这些小木块
2 搜索到总量一半的时候还没有结果的话,那么结果就是sum
3 长度相同的木棍就没必要在处理一遍
4 从大到小的排序处理会更好
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m,maxx,sum,flag;
int a[1010],book[1010];
bool cmp(int x,int y)
{
return x>y;
}
void dfs(int x,int y,int z,int u)
{
int i;
if(u*z==sum)
{
flag=1;
maxx=z;
return ;
}
if(flag) return ;
for(i=x; i<=n; i++)
{
if(!book[i]&&a[i]<=y)
{
book[i]=1;
if(a[i]==y)
dfs(1,z,z,u+1);
else
dfs(i+1,y-a[i],z,u);
book[i]=0;
if(y==z)
return ;
while(a[i+1]==a[i])
i++;
}
}
}
int main()
{
while(scanf("%d",&n)&&n)
{
sum=0;
memset(book,0,sizeof(book));
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a+1,a+n+1,cmp);
int l=a[1];
flag=0;
maxx=sum;
while(!flag)
{
if(sum%l==0)
{
dfs(1,l,l,0);
}
l++;
if(l>sum/2)
break ;
}
printf("%d\n",maxx);
}
return 0;
}