找球号(一)
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
在某一国度里流行着一种游戏。游戏规则为:在一堆球中,每个球上都有一个整数编号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
-
第一行有两个整数m,n(0<=n<=100000,0<=m<=1000000);m表示这堆球里有m个球,n表示这个游戏进行n次。
解法一:set
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
int n,m,a,k;
cin>>m>>n;
set<int>s;
s.clear();
for(int i=0;i<m;++i){
cin>>a;
s.insert(a);
}
while(n--){
int flag=0;
cin>>k;
if(s.find(k)!=s.end()) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
解法二:二分
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int a[1000010];
int main()
{
int n,m;
scanf("%d%d",&m,&n);
for(int i=0;i<m;++i)
scanf("%d",&a[i]);
sort(a,a+m);
while(n--){
int st,ed,mid,k,flag=0;
st=0; ed=m;
scanf("%d",&k);
while(st<=ed){
mid=st+(ed-st)/2;
if(a[mid]==k){
flag=1;
break;
}
else if(a[mid]<k)
st=mid+1;
else
ed=mid-1;
}
if(flag==1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}