(DP)—HDU-5616-Jam's balance

Jam's balance

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2404    Accepted Submission(s): 982

 

Problem Description

Jim has a balance and N weights. (1≤N≤20)
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≤T≤5) , 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(1≤wi≤100) 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

Source

BestCoder Round #70

 

Recommend

hujie   |   We have carefully selected several similar problems for you:  6447 6446 6445 6444 6443 

Statistic | Submit | Discuss | Note

题解:正着一遍 01 背包,反着一遍 01 背包

#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
#include<set>
#include<map>
#include<math.h>
#include<stack>
#include<vector>
#include<bitset>
#include<iostream>
#define ullmax 1844674407370955161
#define llmax 9223372036854775807
#define llmaxx 922337203685477580
#define intmax 2147483647
#define intmaxx 214748364
#define re register
#define pushup() tree[rt]=max(tree[rt<<1],tree[rt<<1|1])
using namespace std;
int dp[2005],a[25];
int main(){
    int t,n,m,k;
    scanf("%d",&t);
    while(t--){
        memset(dp,0,sizeof(dp));
        scanf("%d",&n);
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        dp[0]=1;
        for(int i=0;i<n;i++){
            for(int j=2000;j>=a[i];j--){
                dp[j]|=dp[j-a[i]];
            }
        }
        for(int i=0;i<n;i++){
            for(int j=0;j<=2000;j++){
                if(j+a[i]>2000)  continue;
                dp[j]|=dp[j+a[i]];
            }
        }
        scanf("%d",&m);
        while(m--){
            scanf("%d",&k);
            if(dp[k])
                printf("YES\n");
            else
                printf("NO\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/black_horse2018/article/details/82251211