HDU 5616 Jam's balance(简单DP)

本文介绍了一个使用天平和有限数量的砝码来判断能否测量特定重量的算法。通过递增更新状态的方式,记录哪些重量可以通过现有砝码组合实现。最终确定目标重量是否可测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 M. M is the weight of the object being measured.
 
Output
You should output the "YES"or"NO".
 
Sample Input
1 2 1 4 3 2 4 5
 
Sample Output
NO YES YES
Hint
For the Case 1:Put the 4 weight alone For 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值