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.
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.
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
思路:二进制枚举 |
- 因为天平两端均可放置砝码
- 所以二进制枚举所有情况以后再减去的已知砝码的重量(例如有重量为x和y的砝码,则可以称出的重量为:x+y |x-y| x y)
#include<iostream>
#include<cstring>
using namespace std;
const int MAXN = 2050;
int a[MAXN];
bool vis[MAXN];
int main(){
int T,n,m,w;
cin>>T;
while(T--){
memset(vis,0,sizeof(vis));
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<(1<<n);i++){
int sum=0;
for(int j=0;j<n;j++){
if(i&(1<<j)){
sum+=a[j];
}
}
vis[sum] = true;
for(int j=0;j<n;j++){
if(sum-a[j]>0) vis[sum-a[j]] = true;
}
}
cin>>m;
while(m--){
cin>>w;
if(vis[w]) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}