元素查找(codevs 1230)

1230 元素查找

 

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 钻石 Diamond
 
 
 
题目描述 Description

给出n个正整数,然后有m个询问,每个询问一个整数,询问该整数是否在n个正整数中出现过。

输入描述 Input Description

第一行两个整数 n 和m。

第二行n个正整数(1<=n<= 100000)

第三行m个整数(1<=m<=100000)

输出描述 Output Description

一共m行,若出现则输出YES,否则输出NO

样例输入 Sample Input

4 2

2 1 3 4

1 9

样例输出 Sample Output

YES

NO

//简单二分查找 
#include<cstdio>
#include<iostream>
#include<algorithm>
#define M 100010
using namespace std;
int a[M],n,m;
void search(int x)
{
    int l=0,r=n;
    while(l<=r)
    {
        int mid=(l+r)/2;
        if(x>=a[mid])l=mid+1;
        else r=mid-1;
    }
    if(x==a[l-1])printf("YES
");
    else printf("NO
");
}
int main()
{
    freopen("jh.in","r",stdin);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
      scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    for(int i=1;i<=m;i++)
    {
        int x;
        scanf("%d",&x);
        search(x);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/harden/p/5619387.html