Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.
You are given the sequence A and q questions where each question contains Mi.
Input
In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.
Output
For each question Mi, print yes or no.
Constraints
- n ≤ 20
- q ≤ 200
- 1 ≤ elements in A ≤ 2000
- 1 ≤ Mi ≤ 2000
Sample Input 1
5
1 5 7 10 21
8
2 4 17 8 22 21 100 35
Sample Output 1
no
no
yes
yes
yes
yes
no
no
Notes
You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:
solve(0, M)
solve(1, M-{sum created from elements before 1st element})
solve(2, M-{sum created from elements before 2nd element})
...
The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.
For example, the following figure shows that 8 can be made by A[0] + A[2].
题目大意:给出长度为n的数列,再输入q个数m,判断A中任意几个元素相加能否得到m。如果可以输出yes否则输出no
穷举搜索法:
用函数solve(i,m)代表用第i个数后边的数能得到m时返回true,可将solve(i,m)再分解为solve(i+1,m)和solve(i+1,m-A[i])。其中solve(i+1,m-A[i])的意思是使用了第i个数A[i],由此递归实现
solve(i,m)中当m为0时,代表用现有的数已经凑出来了m;若m>0,但n个数均已用,则说明用现有的数无法凑出m
一个小bug:因为我的程序是从第一个数开始而不是第0个数开始,所以判断不能凑出时应该条件时i>=n+1,这句话说明所有的n个数都已被用
#include<iostream>
using namespace std;
int n;
int A[23];
int solve(int i,int m){
if(m==0){
return 1;
}
else if(i>=n+1){
return 0;
}
else{
int res=solve(i+1,m)||solve(i+1,m-A[i]);
return res;
}
}
int main(){
int q,m;
cin>>n;
for(int i=1;i<=n;i++){
cin>>A[i];
}
cin>>q;
while(q--){
cin>>m;
if(solve(1,m)){
cout<<"yes"<<endl;
}
else{
cout<<"no"<<endl;
}
}
return 0;
}
动态规划
将算出来的solve(i,m)存入dp[i][m]中,避免重复计算
#include<iostream>
#include<cstring>
using namespace std;
int dp[23][2050];
int n;
int A[23];
int solve(int i,int m){
if(m==0){
dp[i][m]=1;
}
else if(i>=n+1){
dp[i][m]=0;
}
else{
int res=solve(i+1,m)||solve(i+1,m-A[i]);
dp[i][m]=res;
}
// else if(solve(i+1,m)==1) {
// dp[i][m]=1;
// }
// else if(solve(i+1,m-A[i])==1){
// dp[i][m]=1;
// }
// else{
// dp[i][m]=0;
// }
return dp[i][m];
}
int main(){
memset(dp,0,sizeof(dp));
int q,m;
cin>>n;
for(int i=1;i<=n;i++){
cin>>A[i];
}
cin>>q;
while(q--){
cin>>m;
if(solve(1,m)==1){
cout<<"yes"<<endl;
}
else{
cout<<"no"<<endl;
}
}
return 0;
}