1. 程式人生 > >母函式——秤砣問題——The Balance

母函式——秤砣問題——The Balance

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,一個2,要想稱出1,很明顯放一個重量為1的即可,但是天平左邊放1,右邊放2,同樣可以稱出1;

可以稱出的質量還可得到這樣一個式子 M=\left | m1-m2 \right | ; m1,m2 分別為兩個秤砣重量;

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=20000;
int n;
int a[maxn];
int t[maxn];
int v[maxn];

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        int s=0;
        memset(t,0,sizeof t);
        memset(v,0,sizeof v);
        for(int i=1;i<=n;++i)
            scanf("%d",&a[i]),s+=a[i];
        v[0]=1;
        v[a[1]]=1;
        for(int i=2;i<=n;++i)
        {
            for(int j=0;j<=s;++j)
                for(int k=0;k+j<=s&&k<=a[i];k+=a[i])
            {
                t[abs(j-k)] += v[j];
                t[j+k]+=v[j];
            }
            for(int j=0;j<=s;++j)
            {
                v[j]=t[j];
                t[j]=0;
            }
        }
        int cnt=0;
        for(int i=0;i<=s;++i)
            if(v[i]==0) ++cnt;
        cout<<cnt<<endl;
        if(cnt==0) continue;
        else
        {
            for(int i=0;i<=s;++i)
            {
                if(!v[i])
                {
                    printf("%d",i);
                    --cnt;
                    if(cnt) printf(" ");
                    else puts("");
                }
            }
        }
    }
}