HDU 5616 Jam's balance(01背包)

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=5616

题意:用已知的砝码能否称出给出的重量,砝码可以放在2边,看到好多人用异或写,参考一下

思路:在已有背包里面减和加就行

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>

const int inf = 0x7f7f7f7f;//2139062143
typedef long long ll;
using namespace std;

int a[25];
int dp[25][2000];

int main()
{
    int t,n,m;
    int i,j;
    scanf("%d",&t);
    while(t--)
    {
        memset(dp,0,sizeof(dp));
        int sum = 0;
        scanf("%d",&n);
        for(i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            sum += a[i];
        }
        dp[0][0] = 1;
        for(i=1; i<=n; i++)
        {
            for(j=0; j<=sum; j++)
            {
                if(dp[i-1][j])
                {
                    dp[i][j] = 1;
                    if(j+a[i] <= sum)
                    {
                        dp[i][j+a[i]] = 1;
                    }
                    if(j-a[i] >= 0)
                    {
                        dp[i][j-a[i]] = 1;
                    }
                }
            }
        }
        scanf("%d",&m);
        while(m--)
        {
            int k;
            scanf("%d",&k);
            if(k >= 0 && k <= sum && dp[n][k])
            {
                puts("YES");
            }
            else
            {
                puts("NO");
            }
        }
    }
    return 0;
}

用异或写的代码,很精简

地址:http://blog.csdn.net/dml_96/article/details/50615898

你可能感兴趣的:(HDU 5616 Jam's balance(01背包))