hdu 题目1445 Stick(DFS+剪枝)
2013-08-07 21:45
239 查看
Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4753 Accepted Submission(s): 1316
[align=left]Problem Description[/align]
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.
[align=left]Input[/align]
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.
[align=left]Output[/align]
The output file contains the smallest possible length of original sticks, one per line.
[align=left]Sample Input[/align]
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
[align=left]Sample Output[/align]
6
5
黑书P181上面有分析
DFS+剪枝
参考黑书分析之后的个人算法:
1.初始木棍的长度必须是所有木棍长度之和的约数
2.按木棍的递减顺序搜索
3.构造一根初始木棍的第一根木棍必须是最长的
4.2根长度相同的木棍没必要重复搜索
#include<stdio.h> #include<algorithm> #include<string.h> int n,a[66],sum; bool vis[66]; int cmp(const void* a,const void *b) { return *(int *)b - *(int *)a; } bool dfs(int x,int p,int len,int num)//num代表当前找到的边长数目,len代表要找的长度 { bool flag; //标记是否找到符合题意的 if(num==sum/len-1) return 1; //需要找到的数目为 sum/len ,只需找到 sum/len-1剩下的一定是组合成一根 for(int i=p+1;i<=n;i++) if(!vis[i] && x>=a[i]) { vis[i]=1; if (x==a[i]) flag = dfs(len,0,len,num+1); //找到一根,x复原 else flag = dfs(x-a[i],i,len,num); //找到一根len长的还需要 x-a[i] 长度 vis[i]=0; if (p==0) return flag;//当搜索返回到最开始的一层时, else if (flag) return 1; while (a[i]==a[i+1]) i++;//相同的木棍不需要再继续判断 } return 0; } int main() { while(scanf("%d",&n),n) { int i; sum=0; for(i=1;i<=n;i++){ scanf("%d",&a[i]); sum += a[i]; } qsort(a+1,n,sizeof(int),cmp); //按递减序列进行查找 memset(vis,0,sizeof(vis)); int ans = sum; for(i=a[1];i<=sum/2;i++) if(sum%i==0 && dfs(i,0,i,0)){ ans = i; break; } printf("%d\n",ans); } return 0; }
相关文章推荐
- HDU 5655 CA Loves Stick(思维题目)【bestcoder】
- hdu 1445 sticks (经典dfs+剪枝)
- HDU 题目分类
- HDU 1010 Tempter of the Bone(DFS+剪枝)
- HDU 1070 一道结构体的题目
- hdu 题目4217 Data Structure?(线段树,单点更新)
- hdu 题目1596 find the safest road (最短路径 dijkstra)
- hdu-题目分类
- hdu 3415 蛋疼的题目
- 文章标题 HDU 1455 : Sticks(dfs+剪枝)
- hdu 题目1053Entropy (赫夫曼树)
- HDU 题目分类
- HDU 动态规划(46道题目)倾情奉献
- HDU 题目1087 Super Jumping! Jumping! Jumping!
- HDU-1010 Tempter of the Bone (DFS+剪枝)
- hdu 题目1907 Johu (取火柴游戏,取最后一个胜)
- HDU题目分类(转载)
- hdu 题目1171 Big Event in HDU(母函数及其应用)
- hdu 部分题目分类
- hdu 2076 夹角有多大(题目已修改,注意读题)