当前位置: 代码迷 >> 综合 >> hdoj5616Jam's balance【dp】
  详细解决方案

hdoj5616Jam's balance【dp】

热度:56   发布时间:2023-12-17 08:30:54.0

Jam's balance

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


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


#include<cstdio>  
#include<cstdlib>  
#include<cstring>  
#include<algorithm>  
#include<cmath>  
using namespace std;  
const int maxn=25;  
int num[maxn];  
bool dp[maxn][maxn*200];  
int main()  
{  int n,i,j,k,m,t;  scanf("%d",&t);  while(t--){  scanf("%d",&n);  int sum=0;  for(i=1;i<=n;++i){  scanf("%d",&num[i]);  sum+=num[i];  }memset(dp,false,sizeof(dp));dp[0][sum]=true;  for(i=1;i<=n;++i){  for(j=0;j<=sum*2;++j){  if(dp[i-1][j]){  dp[i][j]=true;  dp[i][j+num[i]]=true;  if(j>=num[i])dp[i][j-num[i]]=true;  }  }  }  scanf("%d\n",&m);  while(m--){  scanf("%d",&k);  if(k>sum){  printf("NO\n");}  else {  if(dp[n][k+sum])printf("YES\n");else printf("NO\n");  }  }  }  return 0;  
}