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