HDU 5616 Jam's balance

本文介绍了一种使用动态规划解决测量物体重量的问题。通过给定的若干个不同重量的砝码,在天平上判断能否测量出特定的目标重量。文章详细展示了输入输出格式及样例,并提供了完整的代码实现。
Problem Description

Jim has a balance and N weights. (1 \leq N \leq 20)(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(1 \leq T \leq 5)T(1T5), means T test cases. For each test case : The first line is NN, means the number of weights. The second line are NN number, i'th number w_i (1 \leq w_i \leq 100)wi(1wi100) means the i'th weight's weight is w_iwi. The third line is a number MMMM 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

对DP熟悉,还是要多练习一下,都没有下意识的想用DP。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <cstdlib>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
int T, n, m, dp[21][4005], x;
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        memset(dp, 0, sizeof(dp));  
        dp[0][2000]=1;
        for(int i=0;i<n;i++)
        {
            scanf("%d", &x);
            for(int j=x;j<=4000-x;j++)
                if(dp[i][j])    dp[i+1][j-x]=dp[i+1][j+x]=dp[i+1][j]=1;//不断对可能取到的重量做标记
        }

        scanf("%d",&m);
        while(m--)
        {
            scanf("%d",&x);
            if(x>=0&&x<=2000)
            {
                if(dp[n][2000-x]||dp[n][2000+x]) printf("YES\n");
                else printf("NO\n");
            }
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值