HDU 1455 http://acm.hdu.edu.cn/showproblem.php?pid=1455
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> #define N 70 int f, vis[N], v, n, a[N]; int cmp(const void *a, const void *b) { return *(int *)b - *(int *)a; } void DFS(int w, int sum) { int i; if(sum == 0) f = 1; else { for(i = 0 ; i < n && f == 0; i++) { if(!vis[i] && w - a[i] >= 0) { vis[i] = 1; if(w - a[i] == 0) DFS(v, sum - a[i]); else DFS(w - a[i], sum - a[i]); vis[i] = 0; if(w == a[i]) return ; if(w == v && a[i] < v) return ; while(a[i] == a[i + 1]) i++; } } } } int main() { int i, sum; while(scanf("%d", &n), n) { sum = f = 0; for(i = 0 ; i < n ; i++) { scanf("%d", &a[i]); sum += a[i]; } qsort(a, n, sizeof(a[0]), cmp); for(v = a[0] ; v <= sum ; v++) { if(sum % v == 0) { if(sum == v) printf("%d\n", sum); else { memset(vis, 0, sizeof(vis)); DFS(v, sum); if(f == 1) { printf("%d\n", v); break; } } } } } return 0; }