HDU-5616 Jam's balance(母函数)

来源:互联网 发布:淘宝怎么查看排名 编辑:程序博客网 时间:2024/06/05 08:43

友情链接

Jam's balance

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2093    Accepted Submission(s): 861


Problem Description
Jim has a balance and N weights. (1N20)
The balance can only tell whether things on different side are the same weight.
Weights can be put on left side or right side arbitrarily.
Please tell whether the balance can measure an object of weight M.
 

Input
The first line is a integer T(1T5), means T test cases.
For each test case :
The first line is N, means the number of weights.
The second line are N number, i'th number wi(1wi100) means the i'th weight's weight is wi.
The third line is a number MM is the weight of the object being measured.
 

Output
You should output the "YES"or"NO".
 

Sample Input
121 43245
 

Sample Output
NOYESYES
Hint
For the Case 1:Put the 4 weight aloneFor the Case 2:Put the 4 weight and 1 weight on both side


题意:有一个天平,给你n个砝码,问你能否量出某个质量的物品。


思路:这道题可以用普通型母函数去做,不过因为是天平,所以每个砝码可以放左边也可以放右边,也就是说每个砝码的质量可以加也可以减,所以说在进行b[k + j*v[i]] += a[k];这一步的时候,要考虑减的情况,加上b[abs(k - j*v[i])] += a[k];这一步就行了,这题没有给砝码个数的数据范围,但是总质量不会超过1000。


#include <bits\stdc++.h>#define N 1000using namespace std;int Num,n1[N],n2[N],v[N],P,a[N],b[N],L;void solve(){    a[0] = 1;    L = 0;    for (int i = 1; i <= Num; i++)    {        int R = min(L + n2[i] * v[i], P);        memset(b, 0, sizeof(int)*(R + 1));        for (int j = n1[i]; j <= n2[i] && j*v[i] <= R; j++)            for (int k = 0; k <= L&&k + j*v[i] <= R; k++)            {                b[k + j*v[i]] = b[k + j*v[i]] + a[k];                b[abs(k - j*v[i])] += a[k];            }        memcpy(a,b,sizeof(int)*(R + 1));        L = R;    }}int main(){    int T,Q,x;    scanf("%d", &T);    while (T--)    {        P = 0;        scanf("%d", &Num);        for (int i = 1; i <= Num; i++)        {            n1[i] = 0;            n2[i] = 1;            scanf("%d", &v[i]);            P += v[i];        }        solve();        scanf("%d", &Q);        while (Q--)        {            scanf("%d", &x);            printf("%s\n",a[x]&&x<=L?"YES":"NO");        }    }}