Jim has a balance and N weights. (1≤N≤20)(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.
Input
The first line is a integer T(1≤T≤5)T(1≤T≤5), means T test cases.
For each test case :
The first line is NN, means the number of weights.
The second line are NN number, i'th number wi(1≤wi≤100)wi(1≤wi≤100) means the i'th weight's weight is wiwi.
The third line is a number MM. 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
题解:01背包类型的题,正着扫一遍求和,倒着扫一遍求差就行了;
#include <iostream>
#include <cstring>
using namespace std;
int t, n, m;
int a[25], dp[2500];
void solve()
{
memset(dp,0,sizeof(dp));
dp[0]=1;
for(int i=0; i<n; i++)
for(int j=2100; j>=a[i]; j--)
dp[j]|=dp[j-a[i]];//正着扫一遍;
for(int i=0; i<n; i++)
for(int j=1; j<=2100; j++)
dp[j]|=dp[j+a[i]];;//倒着扫一遍;
}
int main()
{
cin>>t;
while(t--)
{
cin>>n;
for(int i=0; i<n; i++)
cin>>a[i];
solve();
cin>>m;
while(m--)
{
int x;
cin>>x;
if(dp[x]) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}