Problem Description
Now you are asked to measure a dose of medicine with a balance and a number of weights. Certainly it is not always achievable. So you should find out the qualities which cannot be measured from the range [1,S]. S is the total quality of all the weights.
Input
The input consists of multiple test cases, and each case begins with a single positive integer N (1<=N<=100) on a line by itself indicating the number of weights you have. Followed by N integers Ai (1<=i<=N), indicating the quality of each weight where 1<=Ai<=100.
Output
For each input set, you should first print a line specifying the number of qualities which cannot be measured. Then print another line which consists all the irrealizable qualities if the number is not zero.
Sample Input
3
1 2 4
3
9 2 1
Sample Output
0
2
4 5
特殊的母函数, 要考虑到砝码可以放天平左边也可以放天平右边。
所以构造母函数的时候幂要有负数。
比如第二个实例:构造的母函数为(1 + x^9 + x^-9)* (1 + x^2 + x^-2) + (1 + x + x^-1)
AC代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
int num[20000];
int c1[20000];
int c2[20000];
int ans_c, ans[20000];
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
int i, j;
int sum = 0;
for(i = 0; i < n; i++)
{
scanf("%d", &num[i]);
sum += num[i];
}
memset(c1, 0, sizeof(c1));
memset(c2, 0, sizeof(c2));
c1[0] = 1;
for(i = 0; i < n; i++)
{
for(j = 0; j <= sum; j++)
{
c2[j] += c1[j];
c2[j + num[i]] += c1[j];
c2[abs(j - num[i])] += c1[j];//虽然这样会重复计算,但题目只要求判断是否能构成,没有问具体有几种构成,所以重复计算也没关系。
}
for(j = 0; j <= sum; j++)
{
c1[j] = c2[j];
c2[j] = 0;
}
}
for(i = 1, j = ans_c = 0;i <= sum;i++)
{
if(c1[i] == 0)
{
ans_c++;
ans[j++] = i;
}
}
printf("%d\n", ans_c);
if(ans_c)
{
printf("%d", ans[0]);
for(i = 1;i < j;i++)
printf(" %d", ans[i]);
printf("\n");
}
}
return 0;
}