HDU 1709 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

 

 

特殊的母函数, 要考虑到砝码可以放天平左边也可以放天平右边。

 

所以构造母函数的时候幂要有负数。

 

比如第二个实例:构造的母函数为(1 + x^9 + x^-9)* (1 + x^2 + x^-2) + (1 + x + x^-1)

 

AC代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
int num[20000];
int c1[20000];
int c2[20000];
int ans_c, ans[20000];
int main()
{
    int n;
    while(scanf("%d", &n) != EOF)
    {
        int i, j;
        int sum = 0;
        for(i = 0; i < n; i++)
        {
            scanf("%d", &num[i]);
            sum += num[i];
        }
        memset(c1, 0, sizeof(c1));
        memset(c2, 0, sizeof(c2));
        c1[0] = 1;
        for(i = 0; i < n; i++)
        {
            for(j = 0; j <= sum; j++)
            {
                c2[j] += c1[j];
                c2[j + num[i]] += c1[j];
                c2[abs(j - num[i])] += c1[j];//虽然这样会重复计算,但题目只要求判断是否能构成,没有问具体有几种构成,所以重复计算也没关系。
            }
            for(j = 0; j <= sum; j++)
            {
                c1[j] = c2[j];
                c2[j] = 0;
            }
        }
        for(i = 1, j = ans_c = 0;i <= sum;i++)
        {
            if(c1[i] == 0)
            {
                ans_c++;
                ans[j++] = i;
            }
        }
        printf("%d\n", ans_c);
        if(ans_c)
        {
            printf("%d", ans[0]);
            for(i = 1;i < j;i++)
                printf(" %d", ans[i]);
            printf("\n");
        }

    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值