《算导》练习题 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


原创粉丝点击