HDU 5616 Jam's balance(dp)

Jam's balance

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


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 MM 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
思路:dp【i】【j】表示選到第i個砝碼,可以稱重重量爲j的物品的狀態,只有0或1代表YES和NO,然後狀態轉移,每個砝碼可以不選,和物品放一邊,不和物品放一邊三種選擇,然後狀態轉移,預處理好dp數組後,每個查詢都是O(1)了。
<pre name="code" class="cpp">#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstring>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cmath>
using namespace std;
const double eps = 1e-10;
const int inf = 0x3f3f3f3f, N = 6e4;
typedef long long ll;
using namespace std;
int main()
{
    int w[22], dp[22][2020], sum;
    int t, n, m, x;
    cin>>t;
    while(t--)
    {
        sum = 0;
        scanf("%d", &n);
        for(int i =  1; i<=n; i++)
            scanf("%d", &w[i]), sum += w[i];
        memset(dp, 0, sizeof(dp));
        dp[0][0] = 1;
        for(int i = 1; i<=n; i++)
            for(int j = 0; j<=sum; j++)
            {
                dp[i][j] |= dp[i-1][j];
                dp[i][j] |= dp[i-1][abs(j-w[i])];
                if(j + w[i]<=sum)
                    dp[i][j] |= dp[i-1][j+w[i]];
            }
        scanf("%d", &m);
        while(m--)
        {
            scanf("%d", &x);
            if(dp[n][x] && x <= sum && x > 0)
                puts("YES");
            else puts("NO");
        }
    }
    return 0;
}




 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章