您的位置:首页 > 其它

HDU - 1709 The Balance(母函数)

2016-11-19 10:37 477 查看
题目:

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


母函数方法

代码:

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: