题目
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.
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 should 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
Source
Central Europe 1995
题解
我们可以从小到大枚举原始木棒的长度lenlenlen,处理出木棒的总长度sumsumsum,那么显然有 lenlenlen是sumsumsum的约数,所以你要拼成的木棒的个数cnt=sum/lencnt = sum / lencnt=sum/len。
于是我们可以dfsdfsdfs一下, stickstickstick表示当前拼接到了第几个木棒,cabcabcab表示当前所拼接的木棒的长度, lastlastlast为所拼接的上一根木棒。
但是这样直接的dfsdfsdfs会超时,那么我们就来思索一下如何剪枝。
- 假如有长度为222,444的两根木棒,先选222后选444,和先选444后选222所得到的结果显然是一样的。
- 对于所有木棒我们先从大到小排序,然后在搜索一定会降低复杂度。
- 如果当前拼接的第一根木棒就失败那么就判定改搜索分支失败,回溯
- 如果当前拼接完成但是下一个拼接失败,就判定该搜索分支失败,回溯
code
#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <iomanip>
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <bitset>
//#define T 0
#define clean(x, y) memset(x, y, sizeof(x))
const int maxn = 105;
const int inf = 0x3f3f3f3f;
typedef long long LL;
using namespace std;
template <typename T>
inline void read(T &s) {
s = 0;
T w = 1, ch = getchar();
while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
s *= w;
}
int n;
int val;
int sum;
int cnt;
int len;
int a[maxn];
int v[maxn];
inline bool cmp(int x, int y) { return x > y; }
bool dfs(int stick, int cab, int last) {
// printf("%d ())(()())(())) \n", cnt);
if (stick > cnt) return true;
if (cab == len) return dfs(stick + 1, 0, 1);
int fail = 0;
for (int i = last; i <= n; ++i) {
if (!v[i] && fail != a[i] && a[i] + cab <= len) {
v[i] = 1;
if (dfs(stick, a[i] + cab, i + 1)) return true;
fail = a[i];
v[i] = 0;
if (cab == 0 || cab + a[i] == len) return false;
}
}
return false;
}
int main() {
while (1) {
read(n);
if (!n) exit(0);
memset(a, 0, sizeof(a));
sum = 0; val = 0;
for (int i = 1; i <= n; ++i)
read(a[i]), sum += a[i], val = max(val, a[i]);
sort(a + 1, a + n + 1, cmp);
for (len = val; len <= sum; ++len) {
if (sum % len) continue;
else {
memset(v, 0, sizeof(v));
cnt = sum / len;
// printf("%d ======= \n", cnt);
if (dfs(1, 0, 1)) break;
}
}
printf("%d\n", len);
}
return 0;
}