DFS。搜索以棍数为条件循环搜索较好,这样不会超时。
#include <stdio.h>
#include <string.h>
#include <stdlib.h> #define true 1
#define false 0
#define MAXN 70 int alen;
int parts[MAXN];
char visit[MAXN];
int n, m; int dfs(int beg, int cnt, int len) {
int i; if (len == ) {
++cnt;
if (cnt+ == m)
return true; for (i=; i<n; ++i)
if ( !visit[i] )
break; visit[i] = ;
if ( dfs(i+, cnt, alen-parts[i]) )
return true;
visit[i] = ; return false;
} for (i=beg; i<n; ++i) {
if (visit[i] || parts[i]>len)
continue;
if (i && parts[i]==parts[i-] && !visit[i-])
continue;
visit[i] = ;
if ( dfs(i+, cnt, len-parts[i]) )
return true;
visit[i] = ;
} return false;
} int comp(const void *a, const void *b) {
return *(int *)b - *(int *)a;
} int main() {
int sum;
int i; while (scanf("%d", &n)!=EOF && n) {
sum = ;
for (i=; i<n; ++i) {
scanf("%d", &parts[i]);
sum += parts[i];
}
qsort(parts, n, sizeof(int), comp);
m = n+;
while (m > ) {
--m;
if (sum%m)
continue;
alen = sum/m;
if (parts[] > alen)
continue;
memset(visit, , sizeof(visit));
if ( dfs(, , alen) )
break;
}
printf("%d\n", alen);
} return ;
}