木棒POJ1011
思路
题干在这:POJ1011
按着《算法竞赛进阶指南》的代码写的,熟悉一下深搜和剪枝
ac代码
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
int a[100], v[100], n, len, cnt;
bool dfs(int stick, int cab, int last) {
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] && cab + a[i] <= len && a[i] != fail) {
v[i] = 1;
if (dfs(stick, cab + a[i], i + 1))
return true;
fail = a[i];
v[i] = 0;
if (cab == 0)
return false;
}
}
return false;
}
int main() {
while (cin >> n && n) {
int sum = 0, val = 0;
for (int i = 1; i <= n; i++) {
scanf_s("%d", a + i);
sum += a[i];
val = max(val, a[i]);
}
sort(a + 1, a + n + 1);
reverse(a + 1, a + n + 1);
for (len = val; len <= sum; len++) {
if (sum % len)
continue;
cnt = sum / len;
memset(v, 0, sizeof(v));
if (dfs(1, 0, 1))
break;
}
cout << len << endl;
}
}