博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Aizu - ALDS1_5_A Exhaustive Search 穷竭搜索
阅读量:3903 次
发布时间:2019-05-23

本文共 1865 字,大约阅读时间需要 6 分钟。

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

51 5 7 10 2182 4 17 8 22 21 100 35

Sample Output 1

nonoyesyesyesyesnono

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 
#include
#include
#include
using namespace std;const int maxn=25;int n,q;int a[maxn];int flag;int x;void cho (int loc,int sum){ if(sum==x) { flag=1; return; } if(loc>n) return; cho (loc+1,sum); cho (loc+1,sum+a[loc]);}void input (){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&a[i]); scanf("%d",&q); while (q--) { scanf("%d",&x); flag=0; cho (1,0); if(flag) printf("yes\n"); else printf("no\n"); }}int main(){ input(); return 0;}

 

转载地址:http://qpaen.baihongyu.com/

你可能感兴趣的文章
深入理解Mysql索引底层数据结构与算法
查看>>
B+tree结构详解
查看>>
B+树算法在mysql中能存多少行数据?
查看>>
【vue学习】—条件判断、循环遍历
查看>>
【vue学习】—slot插槽的使用
查看>>
【vue学习】—前端模块化
查看>>
STM32 外部中断
查看>>
STM32 PWM
查看>>
STM32 PWM波驱动模拟舵机(库函数版)
查看>>
STM32——ADC
查看>>
破解百度网盘屏蔽文件分享失效被和谐的独家秘籍
查看>>
STM32F10X_XX宏定义的选择
查看>>
在头文件声明全局变量和创建extern
查看>>
stm32 USART 串口通信[操作寄存器+库函数]
查看>>
MATLAB画图常用调整代码
查看>>
WORD2010加载mathtype6.6
查看>>
TTL电平、CMOS电平、RS232电平的区别
查看>>
c语言那些细节之a+1和&a+1的区别
查看>>
交换两个变量的值,不使用第三个变量的四种法方
查看>>
STM32 产生随机数
查看>>