uva 307 Sticks(DFS+ 剪枝)

               

 Sticks 

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 file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting. 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
题目大意:将n节木棒接成m个长度相等的木条,要求木条的长度尽可能的短。

解题思路:DFS没什么好说的了,说一下几个剪枝的地方。

<1>首先,拼成木条的长度必须是所有木棒长度总和的约数,并且大于等于木条中的最大值。

<2>将木棒从打到小排列,可以减少递归的层数。

<3>当第i个木棒未选取时,如果i+ 1木棒与i木棒相同长度。跳过, 没有必要重复考虑。

<4>当遍历到i个木棒时,找不到小木棒和它组成木条时, 可以终止当前判断的木条长度。

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;#define N 105int n, ans, sum, stick[N], vis[N];int cmp(const int &a, const int &b){    return a > b;}bool dfs(int cnt, int pos, int sum){    if (cnt == n)   return true;    for (int i = pos; i < n; i++){ if (vis[i]) continueif (sum + stick[i] < ans){     vis[i] = 1;     if (dfs(cnt + 1, i + 1, sum + stick[i]))  return true;     vis[i] = 0;     while (stick[i] == stick[i + 1] && i + 1 < n){  i++;     } } else if (sum + stick[i] == ans){     vis[i] = 1;     if (dfs(cnt + 1, 0, 0))  return true;     vis[i] = 0;     return false; } if (sum == 0)     return false;    }    return false;}int main(){    while (scanf("%d", &n), n){ // Init; memset(stick, 0, sizeof(stick)); sum = 0// Read. for (int i = 0; i < n; i++){     scanf("%d", &stick[i]);     sum += stick[i]; } sort(stick, stick + n, cmp); // Handle. for (int i = n; i > 0; --i){     if (sum % i == 0 && (sum / i) >= stick[0]){  ans = sum / i;  memset(vis, 0, sizeof(vis));  if (dfs(0, 0, 0)){      printf("%d\n", ans);      break;  }     } }    }    return 0;}

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值