HDU 5616 Jam's balance

Jam's balance


Problem Description
Jim has a balance and N weights. (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.
 
Sample Input
 
   
1 2 1 4 3 2 4 5
 
Sample Output
 
    
NO YES YES

题意:先输入一个T,是数据组数,然后输入一个砝码数N,下面输入N个砝码的质量,然后,再输入一个数M是要求秤的物体,分别输入物体质量。

枚举的方法,每个砝码都有两种情况,放与不放,放又可以分两种情况,放左边,放右边。用一个bool型数组表示现在拥有那几重质量,所有的砝码一次添加,产生新的质量存进去。

#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 2002;
bool a[maxn], vis[maxn];
int w[102];
int main()
{
    int T;
    int n, q;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d", &n);
        for(int i=1; i<=n; i++)
            scanf("%d", &w[i]);
        memset(a, 0, sizeof a);
        memset(vis, 0, sizeof vis);
        a[0] = 1;
        for(int i=1; i<=n; i++)
        {
            memset(vis, 0, sizeof vis);
            for(int j=0; j<=2000; j++)
            {
                if(a[j] == 1)
                {
                    if(j-w[i] >= 0)
                        vis[j-w[i]] = 1;
                    if(j+w[i] <= 2000)
                        vis[j+w[i]] = 1;
                }
            }
            for(int j=0; j<=2000; j++)
            {
                if(vis[j])
                    a[j] = 1;
            }
        }
        scanf("%d", &q);
        while(q--)
        {
            int x;
            scanf("%d", &x);
            if(a[x])
                printf("YES\n");
            else
                printf("NO\n");
        }
    }
    return 0;
}


你可能感兴趣的:(暴力枚举)