问题描述
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.
输入格式
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.
输出格式
The output should contains the smallest possible length of original sticks, one per line.
样例输入
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
样例输出
5
6
_____________________________________________________________________________用dfs剪枝来做(网站上的样例是反的 我查了下原题,样例答案应该是6 5)
根据大佬的代码的理解写的,大佬的注释十分详细,可以去观摩一下经典剪枝算法的例题——Sticks详细注释版_SJ2050的博客-CSDN博客_αβ剪枝经典例题
———————————————————————————————————————————
#include<iostream>
#include<algorithm>
typedef long long ll;
using namespace std;
#define MAXSIZE 64
ll n = 0;//木棍个数
ll sum = 0;//当前组的木棍总长度
ll sofs = 0;//当前最小长度所需的木棒个数
ll ar[MAXSIZE] = { 0 };
bool used[MAXSIZE] = { false };
ll flag = false;
void dfs(ll s, ll zu,ll t,ll cnt) {//s为当前查找的最小长度,zu表示已经拼接好的组数,t表示当前组成木棒的长度,cnt表示开始查找的下标(用于剪枝)
if (zu==sofs) { cout << s << endl; flag = true; return; }
if (flag || cnt >= n ) return;
for (ll i = cnt; i < n; i++) {
if (flag) return;
if (used[i] == false) {
if (t + ar[i] == s) {
used[i] = true;
dfs(s, zu + 1, 0, zu);//下一层选的木棒因该由[zu]开始
used[i] = false;
return;//只有当前的ar[i]才能凑成,之后的数只有小于等于ar[i]的数,所以直接返回就行
}
else if (t + ar[i] < s) {
used[i] = true;
dfs(s, zu, t + ar[i], i + 1);//从i+1的下标开始找符合要求的木棒,因为下标i之前的都已在当前递归中查找过了
used[i] = false;
if (flag) return;
if (t == 0) return;//运行到当前语句且之前的组成长度为0,表示当前木棒不被需要,则跳过
//当前长度不被需要则跳过相同长度
ll j = i + 1;
while (j < n&& ar[j] == ar[i]) ++j;
if (j != i + 1) i = j - 1;
}
}
}
return ;//没有找到
}
bool cmp(ll a, ll b) { return a > b; }
int main() {
ios::sync_with_stdio(false);
while (cin >> n) {
if (n == 0) break;
fill(used, used+MAXSIZE, false);
sum = 0;
flag = 0;//初始化
for (ll i = 0; i < n; i++) { cin >> ar[i]; sum += ar[i]; }
sort(ar, ar + n, cmp);//降序排序
for (ll i = ar[0]; i <= sum ; i++) {
if (sum % i == 0) sofs = sum / i;//可以被整除,符合要求,则开始验证
else continue;
dfs(i, 0, 0, 0);//最小原长度一定不短于最大的被切割的长度
if (flag) break;
}
}
return 0;
}
第一次写剪枝,比较生疏,得多花时间去理解一下