HDU 5616 Jam's balance(简单DP)

来源:互联网 发布:阿里云2m带宽 编辑:程序博客网 时间:2024/06/06 00:02
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 integerT(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 M.M 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 是否可以用已有砝码称出。

从第一个开始更新状态,OK[i][j] 表示考虑到第 i 个时 重量 j 是否可以被称出。1 ~ n 更新一遍即可。

代码:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn1 = 25;const int maxn2 = 2 * 1e3 + 5;bool ok[maxn1][maxn2];int a[maxn1];int n;void init(){    memset(ok,false,sizeof(ok));    ok[0][0] = ok[0][a[0]] = true;    for(int i = 1;i < n; ++i)    {        for(int j = 0;j < maxn2; ++j)        {            if(!ok[i - 1][j]) continue;            ok[i][j] = ok[i - 1][j];            ok[i][j + a[i]] = true;            if(j > a[i]) ok[i][j - a[i]] = true;            else ok[i][a[i] - j] = true;        }    }}int main(){    int t,m,p;    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        for(int i = 0;i < n; ++i) scanf("%d",&a[i]);        init();        scanf("%d",&p);        while(p--)        {            bool r = false;            scanf("%d",&m);            if(ok[n - 1][m]) printf("YES\n");            else printf("NO\n");        }    }    return 0;}

原创粉丝点击