http://acm.hdu.edu.cn/showproblem.php?pid=1455
Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2164 Accepted Submission(s): 493
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
Source
Recommend
lcy
黑书P181上面有分析
DFS+剪枝
参考黑书分析之后的个人算法:
1.初始木棍的长度必须是所有木棍长度之和的约数
2.按木棍的递减顺序搜索
3.构造一根初始木棍的第一根木棍必须是最长的
4.2根长度相同的木棍没必要重复搜索
我的代码
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 int a[70],n,vis[70],sum;
5 int cmp(const void *a,const void *b)
6 {
7 return *(int*)b-*(int*)a;
8 }
9 bool dfs(int x,int p,int y,int m)
10 {
11 bool flag;
12 if (m*y==sum) return 1;
13 for (int i=p+1;i<=n;i++)
14 if (!vis[i] && x>=a[i])
15 {
16 vis[i]=1;
17 if (x==a[i]) flag=dfs(y,0,y,m+1);
18 else flag=dfs(x-a[i],i,y,m);
19 vis[i]=0;
20 if (p==0) return flag;
21 else if (flag) return flag;
22 while (a[i]==a[i+1]) i++;
23 }
24 return 0;
25 }
26 int main()
27 {
28 while (scanf("%d",&n),n)
29 {
30 sum=0;
31 int i;
32 memset(vis,0,sizeof(vis));
33 for (i=1;i<=n;i++) {
34 scanf("%d",&a[i]);
35 sum+=a[i];
36 }
37 qsort(a+1,n,sizeof(a[0]),cmp);
38 int ans=sum;
39 for (i=a[1];i<=sum/2;i++)
40 if (sum%i==0 && dfs(i,0,i,0)) {ans=i; break;}
41 printf("%d\n",ans);
42 }
43 return 0;
44 }