母函数,指数可以为1也可以为-1,扩大指数加消减发现TLE,于是采用绝对值就过了。
1 #include <stdio.h> 2 #include <string.h> 3 4 #define MAXNUM 10001 5 6 int c1[MAXNUM], c2[MAXNUM]; 7 int w[101]; 8 9 int myabs(int x) { 10 return x<0 ? -x:x; 11 } 12 13 int main() { 14 int n, sum, tmp; 15 int i, j, k; 16 17 while (scanf("%d", &n) != EOF) { 18 sum = 0; 19 for (i=1; i<=n; ++i) { 20 scanf("%d", &w[i]); 21 sum += w[i]; 22 } 23 memset(c1, 0, sizeof(c1)); 24 memset(c2, 0, sizeof(c2)); 25 c1[0] = 1; 26 c1[w[1]] = 1; 27 tmp = w[1]; 28 for (i=2; i<=n; ++i) { 29 for (j=0; j<=tmp; ++j) 30 for (k=0; k<=w[i]; k+=w[i]) { 31 c2[k+j] += c1[j]; 32 c2[myabs(k-j)] += c1[j]; 33 } 34 tmp += w[i]; 35 for (j=0; j<=tmp; ++j) { 36 c1[j] = c2[j]; 37 c2[j] = 0; 38 } 39 } 40 k = 0; 41 for (i=1; i<=sum; ++i) { 42 if (c1[i] == 0) 43 c2[k++] = i; 44 } 45 printf("%d ", k); 46 for (i=0; i<k; ++i) 47 if (i) 48 printf(" %d", c2[i]); 49 else 50 printf("%d", c2[i]); 51 if (k) 52 printf(" "); 53 } 54 55 return 0; 56 }