ALDS1_5_A: Exhaustive Search

题解
  1. 这里用的思路是:每次选择针对每个元素,每个元素都只有选与不选两种情况,所以共有2n种选择,并且这里将这些组合通过递归生成。
  2. 递归思路:这里的原问题即为solve(a, n, 0, m),即这2n种组合中是否有和为m的,其中的子问题就是solve(a, n, i, m),即在确定了前i个元素下其后面的元素能否组合出m。然后将solve(a, n, i, m)分治为:solve(a, n, i+1, m)和solve(a, n, i+1, m-a[i]),即每个子问题都将其分治为其下一个元素的选或不选,这样就可以递归实现了。
    1. 由于子问题共有n个,所以原问题在每个子问题的分治下被分成了2n个,类似二叉树型结构
    2. 这里通过i<=n即可对递归进行控制,防止其一直向下分治,当不满足条件时返回值或者不设置递归。
  3. 自己之前做这道题的思路是:每次选择针对所有元素,每次选择都要判断选择哪个元素。这样不但时间复杂度高,还需要对已选择的元素进行区别。只看到了表面的选择一组元素,没有发现选择的本质是每个元素的选与不选(类似二项分布中的组合)。
题目
Exhaustive Search
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].

在这里插入图片描述

代码块
#include <iostream>
using namespace std;

int solve(int *a, int n, int i, int m)
{
    if(m==0)//从输入值m中减去所选元素,当m==0就说明和为m,搜索成功。
        return 1;
    if(i>=n)//i代表所选元素的个数,达到n就返回0,代表不成功
        return 0;
    int res = solve(a, n, i+1, m) || solve(a, n, i+1, m-a[i]);//模拟a中第i+1个元素的选与不选:左边的代表不选,右边的代表选。如果某种情况中有1就返回1,都是0就返回0。
    return res;
}

int main(void)
{
    int i, n, q;
    cin>>n;
    int a[n];
    for(i=0; i<n; i++)
        cin>>a[i];
    cin>>q;
    for(i=0; i<q; i++)
    {
        int m;
        cin>>m;
        if(solve(a, n, 0, m))
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值