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.
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 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
Sample Output
6 5
分析
这个题还是比较有意思的,多根木棒要拼成若干根等长的木棍,用深搜搜索所有可能性,可采取多种剪枝方法,讲义已讲的很全,相关可剪枝原因已在代码中加上注释。
实现
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <functional>
using namespace std;
vector<int> len(
65);
int used[
65];
int L;
int n;
bool dfs(
int rest,
int needLen,
int lastIndex)
{
if (rest ==
0 && needLen ==
0) {
return true;
}
if (needLen ==
0) {
needLen = L;
}
int startInex = needLen == L ?
0 : lastIndex +
1;
for(
int i = startInex; i < n; i++) {
if (i >
0 && !used[i-
1] && len[i-
1] == len[i]) {
continue;
}
if (!used[i] && len[i] <= needLen) {
used[i] =
1;
if (dfs(rest -
1, needLen - len[i], i)) {
return true;
}
else {
used[i] =
0;
if (needLen == L
|| needLen == len[i]) {
return false;
}
}
}
}
return false;
}
int main()
{
while (
cin >> n && n >
0) {
len.clear();
int minLen =
0;
int totalLen =
0;
int tempLen;
for(
int i =
0;i<n; i++) {
cin >> tempLen;
len.push_back(tempLen);
totalLen += tempLen;
}
sort(len.begin(), len.end(), greater<
int>());
for(L = len[
0]; L <= totalLen /
2; L++) {
if (totalLen % L) {
continue;
}
memset(used,
0,
sizeof(used));
if (dfs(n, L, -
1)) {
minLen = L;
break;
}
}
if (L > totalLen /
2) {
minLen = totalLen;
}
cout << minLen << endl;
}
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-970930.html