hdu dfs入门java_hdu 1455(DFS+好题+经典)

Sticks

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

Total Submission(s): 9414    Accepted Submission(s): 2776

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

题意:给多组数据,每组数据代表一些小木棍,能否将它们全部用完组成(尽量)多个相同长度的长棍,并输出长棍的长度。

题解:有强剪枝,,多一个if(l==0) return false就AC了。。真的是NB啊,这处剪枝的作用:当len==0时,证明当前是在构造一根新的木棍,而这个第一根和其后面的所有的木棍都无法组合,那么这根木棍永远都无法用到了,所以我们直接返回上一层。下面那个while循环的剪枝作用就是当前木棍无法用到,那么其后面的所有的木棍都无法用到了,跳过即可。

#include #include#include#include#include

using namespacestd;intn,sum,num;int v[100];bool vis[100];int cmp(int a,intb){return a>b;

}bool dfs(int len,int l,int cnt,intpos){if(cnt==num) return true;for(int i=pos;i

vis[i]= true;if(dfs(len,0,cnt+1,0)) return true;

vis[i]= false;

return false; ///加了这个才能过poj,这个代表如果当前长度的木棍以后的木棍都拼不出这个长度了,那么就没必要试这个长度了,(后面都比当前小...)直接跳出..ORZ

}else if(len>l+v[i]){

vis[i]= true;if(dfs(len,l+v[i],cnt,i+1)) return true;

vis[i]= false;if(l==0) return false;while(v[i]==v[i+1])i++;

}

}return false;

}intmain(){while(scanf("%d",&n)!=EOF,n){

sum= 0;for(int i=0;i

scanf("%d",&v[i]);

sum+=v[i];

}

sort(v,v+n,cmp);int ans =sum;for(int i=v[0];i<=sum;i++){if(sum%i!=0) continue;

num= sum/i;

memset(vis,false,sizeof(vis));if(dfs(i,0,0,0)) {

ans=i;break;

}

}

printf("%d\n",ans);

}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值