《算导》练习题 2.3-7
来源:互联网 发布:数据库触发器 编辑:程序博客网 时间:2024/06/03 15:08
题目:
设计算法:查找集合 S 中是否存在两个其和等于 x 的元素。
解析:
先排序(sort),对每个数组元素(s[i]),在数组中二分查找它的补元素(x-s[i]):利用<algorithm>中的binary_search(起始位置,终止位置,目标值)和lower_bound(起始位置,终止位置,目标值)即可快速查找。最后输出相应结果即可。
附上函数讲解:
STL之二分查找(binary_search(),lower_bound(),upper_bound() )
代码:
#include<cstdio>#include<algorithm>#define maxn 10007using namespace std;int a[maxn];bool check(int s[],int n,int x){ sort(s,s+n); for(int i = 0;i < n;i++) { int v = x - s[i]; if(binary_search(s,s+n,v)&&lower_bound(s,s+n,v) != s+i) { return true; } } return false;}int main(){ int n; while(~scanf("%d",&n)) { for(int i = 0; i < n; i++) { scanf("%d",&a[i]); } int m,x; scanf("%d",&m); while(m--) { scanf("%d",&x); if(check(a,n,x)) { printf("Yes "); } else { printf("No "); } } }}测试数据:
5
1 2 3 4 5
12
0 1 2 3 4 5 6 7 8 9 10 11
测试结果:
No No No Yes Yes Yes Yes Yes Yes Yes No No
阅读全文
0 0
- 《算导》练习题 2.3-7
- 《算法导论》练习题2.3-7
- 算法导论 练习题 2.3-7
- 练习题7
- 算法导论之2.3-7练习题
- C++之练习题7
- Opencv练习题3-7
- 练习题2016.11.7
- Linux练习题7
- Java练习题7
- Linux基础练习题(7)
- java练习题7
- C语言练习题(7)
- 练习题
- 练习题
- 练习题
- 练习题
- 练习题
- maven去掉重复依赖的jar包
- React Native遇到的坑
- timestamp的字段设计
- Nginx优化相关
- 洛谷P1092
- 《算导》练习题 2.3-7
- 一些可能帮得上忙的网站
- MyBatis Generator生成代码的几种方式
- Java——线程的加入
- LeetCode--Word Search
- xdoj 1056 寻找BOSS
- .gitignore文件配置
- JFinal连接两个MYSQL数据的前提下连接第三个ORACLE数据库
- jdk配置是path和classpath的含义