DFS深度优先搜索(6)--hdu1455(经典深搜+剪枝)

来源:互联网 发布:sql语句查询时间段 编辑:程序博客网 时间:2024/05/18 21:50

                                                           Sticks

                                                                                  Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)



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
95 2 1 5 2 1 5 2 141 2 3 40
 

Sample Output
65
 

Source
ACM暑期集训队练习赛(七)


题意:有一堆的木棒,长度不一,它们是有一些整齐的木棒截断而成的,求最小的木棒原始长度。
思路很简单,深搜,但是直接深搜的话会tle,首先贪心一发,可以对木棒长度进行排序从大到小,优先使用长度长的木棒,加入当前长度不符合,考虑下一个木棒。然后就是几个剪枝;具体见代码注释:
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int n;int a[65];int vis[65];int flag;bool cmp(int a,int b){return a>b;}void Dfs(int lim,int sum,int cnt)   //lim指当前枚举的木棒长度   {                                   //sum指拼凑出来的木棒长度  超过lim则减去lim if(flag)return;                 //cnt指当前一共用了多少木棍 if(sum>lim) return;if(sum==lim&&cnt==n){flag=1;return;}if(sum==lim)sum=0;int i;for(i=0;i<n;i++){if(vis[i])continue;    //是否用过 vis[i]=1;Dfs(lim,sum+a[i],cnt+1);vis[i]=0;if(sum==0)return;//剪枝二:如果当前搜索时,前边的长度为0,而第一根没有成功的使用,        //说明第一根始终要被废弃,所以这种组合必定不会成功        //此处的剪枝必须有,因为这里的剪枝会节省很多的无用搜索,while(a[i]==a[i+1])i++;    //剪枝三:如果当前和上一次搜到的木棒是一样长的则没必要再搜一次了}}int main(){int i,j,sum;while(scanf("%d",&n)!=EOF){if(!n)break;memset(vis,0,sizeof(vis));sum=0;int Max=-1;for(i=0;i<n;i++){scanf("%d",&a[i]);sum+=a[i];} sort(a,a+n,cmp);  //将木棒按照长度从长到短的顺序排序for(i=a[0];i<=sum;i++)    //从木棒的最长的那根开始搜索,因为最小的组合也会大于等于最长的那根{flag=0; if(sum%i==0)Dfs(i,0,0);  //剪枝一:如果不能被整除说明不能组成整数根木棒,搜下一个if(flag)break;}printf("%d\n",i);}return 0;}





 

0 0
原创粉丝点击