Jam's balance
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1555 Accepted Submission(s): 661
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.
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.
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 YESHintFor the Case 1:Put the 4 weight alone For the Case 2:Put the 4 weight and 1 weight on both side
Source
思路:根据题意可知,每次都会有三个状态,放在左边,放在右边,不放,所以就可以得出递推方程。因此,在输入相应的权重时,可以利用打表把可以测量的所有结果都计算出来。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int a[25],dp[25][2500];
int main(){
int t,m,n,sum,num;
scanf("%d",&t);
while(t --){
scanf("%d",&n);
sum = 0;
for(int i = 1; i <= n; i ++){
scanf("%d",&a[i]);
sum += a[i];
}
memset(dp,0,sizeof(dp));
dp[0][0] = 1;
for(int i = 1; i <= n; i ++){
for(int j = 0; j <= sum; j ++){
if(dp[i-1][j]){
dp[i][j] = 1;
dp[i][j + a[i]] = 1;
if(j > a[i])
dp[i][j - a[i]] = 1;
}
}
}
scanf("%d",&m);
while(m--){
scanf("%d",&num);
if(num > sum)
printf("NO\n");
else if(dp[n][num])
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}