题目大意:有一堆小木棍,把它们接成相同长度的小木棍,问结果的小木棍的最小长度是多少,多组数据
题解:$dfs$,各种剪枝。
卡点:无
C++ Code:
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#define maxn 55
const int inf = 0x3f3f3f3f;
int n, Min, Max, sum;
int cnt[maxn];
bool halt;
void dfs(int res, int sum, int len, int now) {
if (!res) {
printf("%d\n", len);
halt = true;
return ;
}
if (sum == len) return dfs(res - 1, 0, len, Max);
for (int i = now; i >= Min; --i) if (cnt[i] && sum + i <= len) {
--cnt[i];
dfs(res, sum + i, len, i);
if (halt) return ;
++cnt[i];
if (!sum || sum + i == len) return ;
}
}
int main() {
scanf("%d", &n);
while (n) {
Min = inf, Max = sum = 0, halt = false;
__builtin_memset(cnt, 0, sizeof cnt);
for (int i = 0, x; i < n; ++i) {
scanf("%d", &x);
if (x <= 50) {
++cnt[x], sum += x;
Min = std::min(x, Min);
Max = std::max(x, Max);
}
}
for (int i = Max; i <= sum >> 1; ++i) if (sum % i == 0) dfs(sum / i, 0, i, Max);
if (!halt) printf("%d\n", sum);
scanf("%d", &n);
}
return 0;
}