深搜+剪枝,比较容易超时
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
int mark[111];
int len[111];
int ans, num, aim, flag;
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
void dfs(int now, int finish, int k) {
if(finish == ans) {
flag = 1;
return;
}
if(flag == 1) return;
int j;
for(int i = k+1; i < num; i++) {
if(mark[i]) continue;
if(now+len[i] > aim) return;
if(now+len[i] == aim) {
mark[i] = 1;
dfs(0, finish+1, -1);
mark[i] = 0;
}
if(now+len[i] < aim) {
mark[i] = 1;
dfs(now+len[i], finish, i);
mark[i] = 0;
}
if(!now) return;
if(flag) return;
for(j = i+1; j < num; j++)
if(len[j] != len[j-1]) break;
i = j-1;
}
}
int main() {
while(scanf("%d", &num), num != 0) {
int sum = 0;
for(int i = 0; i < num; i++) {
scanf("%d", &len[i]);
sum += len[i];
}
qsort(len, num, sizeof(int), cmp);
int i;
for(i = num; i >= 2; i--) {
if(sum%i) continue;
if(len[num-1] > sum/i) continue;
memset(mark, 0, sizeof(mark));
flag = 0;
ans = i;
aim = sum/i;
dfs(0, 0, -1);
if(flag == 1) break;
}
printf("%d\n", sum/i);
}
return 0;
}