描述
在某一国度里流行着一种游戏。游戏规则为:在一堆球中,每个球上都有一个整数编号i(0<=i<=100000000),编号可重复,现在说一个随机整数k(0<=k<=100000100),判断编号为k的球是否在这堆球中(存在为"YES",否则为"NO"),先答出者为胜。现在有一个人想玩玩这个游戏,但他又很懒。他希望你能帮助他取得胜利。
-
输入
-
第一行有两个整数m,n(0<=n<=100000,0<=m<=1000000);m表示这堆球里有m个球,n表示这个游戏进行n次。
接下来输入m+n个整数,前m个分别表示这m个球的编号i,后n个分别表示每次游戏中的随机整数k
输出
- 输出"YES"或"NO" 样例输入
-
6 4 23 34 46 768 343 343 2 4 23 343
样例输出
-
NO NO YES YES
思路:
二分查找
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
int a[1000001],b[1000001];
int cz(int *a,int n,int s)
{
int x,y,z;
x=0;
z=n-1;
while (x<=z)
{
y=(x+z)/2;
if (s<a[y])
{
z=y-1;
}
else if (s>a[y])
{
x=y+1;
}
else
return 1;
}
return 0;
}
int main()
{
int n,m,i,j;
cin>>n>>m;
for (i=0;i<n;i++)
cin>>a[i];
for (i=0;i<m;i++)
cin>>b[i];
sort(a,a+n);
for (i=0;i<m;i++)
{
if (cz(a,n,b[i]))//发送数组a长度n,要找的数b[i]
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}