HDU1455(DFS)

来源:互联网 发布:表达爱意的网络用语 编辑:程序博客网 时间:2024/06/11 07:30

Sticks

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4434    Accepted Submission(s): 1210


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
 
//深度搜索,注意以当前长度、当前已找根数、当前下标为参数,同时注意先排序以降低时间复杂度,
#include<iostream>#include<algorithm>using namespace std;int len[70];bool hash[70];int sum,n,av;int m;bool cmp(int a,int b){ return a>b;}bool dfs(int s,int le,int num){ int i; if(num==m)  return true; for(i=s+1;i<n;i++) {  if(!hash[i])  {   if(le+len[i]==av)   {    hash[i]=true;    if(dfs(-1,0,num+1))     return true;    hash[i]=false;   }   else if(le+len[i]<av)   {    hash[i]=true;    if(dfs(i,le+len[i],num))     return true;    hash[i]=false;       //无此则会超时,原因是会导致大量本可排除的搜索,假如不能凑齐相同长度,则不必进行直接返回。     if(le==0)return false;    while(i<n-1&&len[i]==len[i-1])     i++;   }  } } return false;}int main(){ int i; int low,high,mid; while(scanf("%d",&n)!=EOF&&n) {  sum=0;  for(i=0;i<n;i++)  {   hash[i]=false;   scanf("%d",&len[i]);   sum+=len[i];  }  sort(len,len+n,cmp);  for(av=len[0];av<=sum;av++)  {   if(sum%av)    continue;   m=sum/av;   if(dfs(-1,0,1))    break;  }  printf("%d\n",av); } return 0;}


 

原创粉丝点击