The Balance

题目链接

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

题意

给你n个不同质量的砝码,他们的数量都是只有一个,问你任意组合这些砝码,所不能称出的质量有多少个,并且输出他们。

分析

对于第二组数据:可以称出的质量: 1 2 3 10 11 12,这是直接让这这些砝码相加能称出的质量,还可以让砝码相减 比如有个天平 一个盘子放9 另一个盘子放1 就可以称出质量为8的,一次类推,,,

和以前做的那种最简单的母函数不太相同,以前的母函数题都是让每项的指数相加,这里不但有相加的情况,还有指数相减的情况。

代码

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while (~scanf("%d", &n))
    {
        vector<int>value, sum;
        int sumValue = 0, maxValue = -1;
        for (int i = 0; i < n; i++)
        {
            int a;
            scanf("%d", &a);
            if (a > maxValue)
                maxValue = a;
            sumValue += a;
            value.push_back(a);
            sum.push_back(1);
        }
        int c1[10001] = {0}, c2[10001] = {0};
        for (int i = 0; i <= sum[0]*value[0]; i += value[0])
            c1[i] = 1;
        for (int i = 1; i < n; i++)
        {
            for (int j = 0; j <= sumValue; j++)
                for (int k = 0; k + j <= sumValue && k <= sum[i]*value[i]; k += value[i])
                {
                    if(k>j)c2[k-j]+=c1[j];//天平的左右盘子都有砝码
                    else c2[j-k]+=c1[j];
                    c2[k + j] += c1[j];//只有一个盘子有砝码
                }
            for (int j = 0; j <= sumValue; j++)
            {
                c1[j] = c2[j];
                c2[j] = 0;
            }
        }
        vector<int>b;
        for (int i = 0; i <=sumValue; i++)
        {
            if (c1[i] == 0)
            {
                b.push_back(i);
            }
        }
        printf("%d\n", b.size());
        if(b.size()>0)
        {
        for (int i = 0; i < b.size() - 1; i++)
            printf("%d ", b[i]);
        printf("%d\n", b[b.size() - 1]);
        }
    }
    return 0;
}
/*
3
1 2 4
3
9 2 1

*/
posted @ 2017-04-14 13:28  -梦里不知身是客  阅读(159)  评论(0编辑  收藏  举报