hdoj 5616 Jam's balance 【母函数】

来源:互联网 发布:linux服务器访问外网 编辑:程序博客网 时间:2024/06/05 05:36

Jam's balance

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


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个已知重量的砝码和一个没有游标的天平,给定m次查询,每次询问能否称出质量为k的物体。


思路:母函数,每次选取的系数可加可减,稍微变一点。


AC代码:


#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <algorithm>#include <queue>#include <stack>#include <map>#include <set>#include <vector>#include <string>#define INF 0x3f3f3f3f#define eps 1e-8#define MAXN (100000+10)#define MAXM (300000+10)#define Ri(a) scanf("%d", &a)#define Rl(a) scanf("%lld", &a)#define Rf(a) scanf("%lf", &a)#define Rs(a) scanf("%s", a)#define Pi(a) printf("%d\n", (a))#define Pf(a) printf("%.2lf\n", (a))#define Pl(a) printf("%lld\n", (a))#define Ps(a) printf("%s\n", (a))#define W(a) while((a)--)#define CLR(a, b) memset(a, (b), sizeof(a))#define MOD 1000000007#define LL long long#define lson o<<1, l, mid#define rson o<<1|1, mid+1, r#define ll o<<1#define rr o<<1|1#define PI acos(-1.0)#pragma comment(linker, "/STACK:102400000,102400000")#define fi first#define se secondusing namespace std;int a[21];int c1[2010], c2[2010];int main(){    int t; Ri(t);    W(t)    {        int n; Ri(n); int sum = 0;        for(int i = 0; i < n; i++) scanf("%d", &a[i]), sum += a[i];        CLR(c1, 0); CLR(c2, 0);        c1[a[0]] = c1[0] = 1;        for(int i = 2; i <= n; i++)        {            for(int j = 0; j <= sum; j++)            {                for(int k = 0; k <= a[i-1] && k + j <= sum; k += a[i-1])                {                    c2[k+j] += c1[j];                    c2[abs(k-j)] += c1[j];                }            }            for(int j = 0; j <= sum; j++)            {                c1[j] = c2[j];                c2[j] = 0;            }        }        int m; Ri(m);        W(m)        {            int k; Ri(k);            printf(c1[k] ? "YES\n" : "NO\n");        }    }    return 0;}


0 0
原创粉丝点击