hdu 5616 Jam's balance ( 动态规划 )

Description

Jim has a balance and N weights.
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 , means T test cases.
For each test case :
The first line is , means the number of weights.
The second line are number, i'th number means the i'th weight's weight is .
The third line is a number . 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


题目大意:有一个只能判断两边是否相等的天平,现在给你一些已知重量的砝码,问你是否可以通过这些砝码测量一个任意给定的重量(input),即可以通过在天平两侧放一定数量的砝码,使天平平衡。

解题思路:本题需要通过计算出这些所给定的砝码,通过加减运算得到的所有的值,考虑到砝码的数量比较小,可以采用暴力的方法,每一个砝码都有三种状态,添加在左边,添加在右边,不使用。可以很容易的得到递归方程。


AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int w[25];
int dp[25][3005];//dp[i][j]表示考虑前i个砝码能否构造出重量j,如果能则值为1,不能值为0
int n;
int main()
{
    int t,m,i,j,test;
    cin>>t;
    while(t--)
    {
        int sum = 0;
        memset(dp,0,sizeof(dp));
        cin>>n;
        for(i=1;i<=n;i++)
        {
            cin>>w[i];
            sum += w[i];
        }
        dp[0][1000] = 1;//这一步很关键,把所有的重量都加了1000,这样可以避免一些负数被过滤掉的因素
        //例如             2 6 7      可以避免-2被过滤掉
        //                 - + +
        for(i=1;i<=n;i++)
        {
            for(j=0;j<=sum+1000;j++)
            {
                if(dp[i-1][j])
                {
                    dp[i][j] = 1;       //表示不使用第i个砝码
                    if(j+w[i]<=sum+1000)//在已有总和基础上加上第i个砝码
                        dp[i][j+w[i]] = 1;
                    if(j-w[i]>=0)       //在已有总和的基础上减去第i个砝码
                        dp[i][j-w[i]] = 1;
                }
            }
        }
        cin>>m;
        while(m--)
        {
            cin>>test;

            if(dp[n][test+1000] && test>=0 && test<=sum)
                cout << "YES" << endl;
            else
                cout << "NO" << endl;

        }
    }
    //cout << "Hello world!" << endl;
    return 0;
}



  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值