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.
这题是母函数的解决的,可以算是变形的母函数吧,代码以及详细解答如下:
#include<stdio.h> #include<string.h> int c1[10001],c2[10001]; int main() { int n,a[101],i,j,k,sum,count; while(scanf("%d",&n)!=EOF) { sum=0;count=0; for(i=1;i<=n;i++) { scanf("%d",&a[i]); sum+=a[i]; } memset(c1,0,sizeof(c1)); memset(c2,0,sizeof(c2)); c1[0]=1;c1[a[1]]=1; for(i=2;i<=n;i++)//表示第i个表达式,即第i个括号 { for(j=0;j<=sum;j++)//j表示允许的最大值,即指数 for(k=0;k+j<=sum&&k<=a[i];k+=a[i])//k表示被乘表达式的指数 { c2[k+j]+=c1[j]; if(j>k) //与一般的母函数不同之处就在这里,从题目给出的输入案例可知,砝码可以放在左右两边 c2[j-k]+=c1[j]; else c2[k-j]+=c1[j]; } for(j=0;j<=sum;j++) { c1[j]=c2[j]; c2[j]=0; } } for(i=1;i<=sum;i++)//后面都是为输出而做出的工作 if(c1[i]==0) count++; printf("%d ",count); for(i=1;i<=sum;i++) if(c1[i]==0&&count==1) { printf("%d ",i); break; } else if(c1[i]==0) { printf("%d ",i); count--; } } return 0; }