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,s](s为砝码的重量和)哪些重量不能被称出来。
思路:这道题的话,和一般的情况(一些砝码,问哪些重量不能被这些砝码组成)不同,这题可以把砝码放在天平的两边,因此可以称出砝码与砝码相减的情况。然后设g(x)=(x^0+x^a[0])*(x^0+x^a[1])*...*(x^0+x^a[n-1]) (这边的n是原来n个砝码的两倍,因为设了n个负的砝码),然后套用母函数的模板即可。
AC代码:
#include <bits/stdc++.h>
typedef long long ll;
const int maxx=10010;
const int inf=0x3f3f3f3f;
using namespace std;
int sup[maxx],temp[maxx];
int a[maxx],b[maxx];
int main()
{
int n;
while(~scanf("%d",&n))
{
int sum=0;
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
memset(sup,0,sizeof(sup));
memset(temp,0,sizeof(temp));
memset(b,0,sizeof(b));
for(int i=0; i<=1; i++)
{
sup[i*a[0]]=1;//只有两种情况:取或不取。
temp[i*a[0]]=0;
}
for(int i=1; i<n; i++)
{
for(int j=0; j<=sum; j++)
{
for(int k=0; j+k*a[i]<=sum && k<=1; k++)
temp[j+k*a[i]]+=sup[j];
}
for(int j=0; j<=sum; j++)
{
sup[j]=temp[j];
temp[j]=0;
}
}
for(int i=sum; i>0; i--)
{
if(sup[i])//i可以被取到
{
for(int j=1; j<i; j++)
{
if(sup[j])//j可以被取到
b[i-j]=1;//则i-j一定可以被取到
}
}
}
int ans=0;
for(int i=1; i<=sum; i++)
{
if(!sup[i] && !b[i])
temp[ans++]=i;//temp存没法被取到的
}
printf("%d\n",ans);
if(ans)
{
int i;
for(i=0; i<ans-1; i++)
printf("%d ",temp[i]);
printf("%d\n",temp[i]);
}
}
return 0;
}