母函数——秤砣问题——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("");
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/codetypeman/article/details/81612214
今日推荐