hdu 1455
Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3542 Accepted Submission(s): 886
Problem 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 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 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
黑书P181上面有分析 DFS+剪枝
参考黑书分析之后的个人算法:
1.初始木棍的长度必须是所有木棍长度之和的约数
2.按木棍的递减顺序搜索
3.构造一根初始木棍的第一根木棍必须是最长的
4.2根长度相同的木棍没必要重复搜索
别人说如果当前要搜索长度为9的棍子,现在已经找到由5 3 1组成的第一根棍子,但是剩下的棍子都没办法组成9这个长度的,那么最终结果就不可能是9???
答案当然可能是9,试试测试数据:5,3,1,4,6,8,最终结果就是9,然而如果已经找到由5 3 1组成的第一根棍子,但是剩下的棍子都没办法组成9这个长度的,这就是要把棒子长度从大到小拍的原因啊,8,6,5,4,3,1. 8和1,6和3 5和4三个组合
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int s[100],flag[100],n,ans,len,found;
bool cmp(int a,int b)
{
return a>b;
}
void dfs(int k,int x,int f)//k是这次搜索应从K序号开始,x是当前组成的棒子的长度,当前正组成的这根棒子是已经组成的第几根
{
int i,pre;
if(f==ans)
found=1;
else if(x==len)
{dfs(0,0,f+1);}
else
{
int pre=-1; //记录前面的棒子的长度,.2根长度相同的木棍没必要重复搜索
for(i=k;i<n;i++)
{
if(!flag[i]&&s[i]!=pre&&x+s[i]<=len) //当回溯到当前棒时,且后面的棒子长度于前面的棒子,剪枝
{
flag[i]=1;
pre=s[i];
dfs(i+1,x+s[i],f);
flag[i]=0;
if(k==0||found) //当回溯到K=0,肯定不会组成多于一根的棒子,构造一根初始木棍的第一根木棍必须是最长的,如果当前最长的棒子不能够组成len长度,那这个len就一定不符合。直接返回
return;
}
}
}
}
int main()
{
int sum,max,i;
while(scanf("%d",&n)==1&&n!=0)
{ sum=0;max=0;found=0;
for(i=0;i<n;i++)
{
scanf("%d",&s[i]);
sum+=s[i];
if(s[i]>max)
max=s[i];
}
sort(s,s+n,cmp);
for(i=max;i<sum;i++)
{
if(sum%i==0)
{
memset(flag,0,sizeof(flag));
len=i;
ans=sum/i;
dfs(0,0,1);
if(found)
break;
}
}
if(found)
printf("%d\n",len);
else
printf("%d\n",sum);
}
return 0;
}