HDU5616--Jam's balance(二进制枚举)

Jam's balance

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


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

题意:有一个没有游标的天平,和n个秤砣,m个询问, 每次一个k,问可否秤出k这个重量。 秤砣可以放两边。

思路:我们可以二进制枚举每一个子集,还要注意一点就是,比如我我们有两个秤砣:2、8;我们不仅记录2、8、2+8、还要记录8-2这种情况,所以每次再跑一遍, 减去每个的重量标记即可。

不懂二进制枚举的请点击这里

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define mem(a,b) memset(a,b,sizeof(a))
const int maxn = 2005;
int a[maxn], vis[2*maxn], n, m, x, t;
int main()
{
    cin >> t;
    while(t--)
    {
        mem(vis,0); cin >> n;
        for(int i = 0; i < n; i++) cin >> a[i];

        for(int i = 1; i < (1 << n); i++)
        {
            int sum = 0;
            for(int j = 0; j < n; j++)
            {
                if(i & (1 << j))
                    sum += a[j];
            }
            vis[sum] = 1;
            for(int j = 0; j < n; j++)
            {
                if(sum - a[j] >= 0)
                    vis[sum-a[j]] = 1;
            }

        }
        cin >> m;
        for(int i = 0; i < m; i++)
        {
            cin >> x;
            if(vis[x]) puts("YES");
            else puts("NO");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sugarbliss/article/details/81101591