HDU - 1709 The Balance(母函数)

来源:互联网 发布:手机淘宝怎么修改分类 编辑:程序博客网 时间:2024/05/22 03:26

题目:

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

31 2 439 2 1

Sample Output

024 5

母函数方法

代码:

#include<stdio.h>int num[20001];int main(){int n, sum, k, r;for (int i = 0; i < 20001; i++)num[i] = 0;while (scanf("%d",&n)!=EOF){sum = 0;num[10000] = 1;while (n--){scanf("%d", &k);for (int i = 10000 - sum; i <= 10000 + sum; i++)if (num[i])num[i - k] = 1;for (int i = 10000 + sum; i >= 10000 - sum; i--)if (num[i])num[i + k] = 1;sum += k;}r = 0;for (int i = 10000; i <= 10000 + sum; i++)r += (num[i] == 0);printf("%d\n", r);if (r == 0)for (int i = 10000; i <= 10000 + sum; i++)num[i] = 0;else for (int i = 10000; i <= 10000 + sum; i++){if (num[i])num[i] = 0;else{printf("%d", i - 10000);r--;printf(r ? " " : "\n");}}for (int i = 10000 - sum; i <= 10000; i++)num[i] = 0;}return 0;}

值得注意的是,数组必须开这么大,少一点都不行,因为100个砝码可能都是100,那样的话sum就是10000

1 0
原创粉丝点击