Sticks——深搜+剪枝

该博客介绍了如何解决一个编程问题,即帮助乔治恢复被随机裁剪成多段、每段不超过50单位长度的木棒到原始状态。通过深搜算法和剪枝策略(如优化搜索顺序、限制长度递减、排除冗余分支等)来找到木棒可能的最小原始长度。博客提供了样例输入和输出,以及代码思路,但未展示具体代码实现。
摘要由CSDN通过智能技术生成

Stick HDU - 1455 Acwing167

题目

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

题目大意

乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍的长度都不超过50个长度单位。

然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。

请你设计一个程序,帮助乔治计算木棒的可能最小长度。

每一节木棍的长度都用大于零的整数表示。

代码思路

深搜+剪枝
剪枝的方法如下:
1.优化搜索顺序,把小木棍长度从小到大排序,优先尝试较长的小木棍
2.从小到大枚举原始木棒的长度len,len应是所有木棍长度的总和sum的约数 即sum%len==0
3.排除等效冗余
(1)限制先后加入的小木棍的长度是递减的
(2)对于当前大木棍,如果尝试一个小木棍分支搜索失败,则不再尝试相同长度的小木棍
(3)如果在当前大木棍中尝试拼接第一根小木棍的递归分支就失败,那么直接判定当前分支就失败,直接回溯
(4)如果拼入一根小木棍后,当前大木棍恰好被拼接完整,并且接下来拼接剩余大木棍的递归分支返回失败,则直接失败回溯

代码1

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

const int N=70;
int w[N];//每个小木棍的长度
bool st[N];//每个小木棍是否被用过
int sum,length;//所有小木棍的总长度,以及枚举的长度length
int n;
//u是当前枚举到第u个大木棍,cur是当前大木棍的长度,start是从第start个小木棍枚举
bool dfs(int u,int cur,int start)
{
   
    if(u*length==sum)return true;
    if(cur==length)return dfs(u+1,0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值