这道题与上一篇文章中的题目类似,我们都可以用dp数组来存储重量j是否能被称出,并直接访问。
上代码
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
const int M = 30;
bool dp[M][N] = {0};//dp[i][j]表示前i个砝码能否测出重量j
//如果dp[i - 1][j] = 1,那么dp[i][j] = 1,dp[i][j + a] = 1,dp[i][abs(j - a)] = 1;
int n, m;
int main(void)
{
cin >> n >> m;
dp[0][0] = 1;
for(int i = 1; i <= n; i++){
int a; cin >> a;
for(int j = 0; j <= 1e5; j++){
if(dp[i - 1][j]){
dp[i][j] = 1;
dp[i][j + a] = 1;
dp[i][abs(j - a)] = 1;
}
}
}
for(int i = 1; i <= m; i++){
int a; cin >> a;//输入物品的重量
if(dp[n][a]) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}