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): 2093    Accepted Submission(s): 861


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.
 

Input
The first line is a integer  T(1T5) , 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(1wi100)  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个砝码,问你能否量出某个质量的物品。


思路:这道题可以用普通型母函数去做,不过因为是天平,所以每个砝码可以放左边也可以放右边,也就是说每个砝码的质量可以加也可以减,所以说在进行b[k + j*v[i]] += a[k];这一步的时候,要考虑减的情况,加上b[abs(k - j*v[i])] += a[k];这一步就行了,这题没有给砝码个数的数据范围,但是总质量不会超过1000。


#include <bits\stdc++.h>
#define N 1000
using namespace std;

int Num,n1[N],n2[N],v[N],P,a[N],b[N],L;
void solve()
{
    a[0] = 1;
    L = 0;
    for (int i = 1; i <= Num; i++)
    {
        int R = min(L + n2[i] * v[i], P);
        memset(b, 0, sizeof(int)*(R + 1));
        for (int j = n1[i]; j <= n2[i] && j*v[i] <= R; j++)
            for (int k = 0; k <= L&&k + j*v[i] <= R; k++)
            {
                b[k + j*v[i]] = b[k + j*v[i]] + a[k];
                b[abs(k - j*v[i])] += a[k];
            }
        memcpy(a,b,sizeof(int)*(R + 1));
        L = R;
    }
}
int main()
{
    int T,Q,x;
    scanf("%d", &T);
    while (T--)
    {
        P = 0;
        scanf("%d", &Num);
        for (int i = 1; i <= Num; i++)
        {
            n1[i] = 0;
            n2[i] = 1;
            scanf("%d", &v[i]);
            P += v[i];
        }
        solve();
        scanf("%d", &Q);
        while (Q--)
        {
            scanf("%d", &x);
            printf("%s\n",a[x]&&x<=L?"YES":"NO");
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值