找球号(一)

时间限制: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 首先数据很多,用scanf和printf 解法一:用set集合
 #include <iostream>
#include <set>
#include <algorithm>
#include <cstdio>
using namespace std; int main(){
int m, n, i, k;
set<int> s;
scanf("%d %d", &m, &n);
while(m--) {
scanf("%d", &i);
s.insert(i);
} while(n--){
scanf("%d", &k);
if(s.find(k) != s.end())
printf("YES\n");
else
printf("NO\n");
}
return ;
}

二分查找也可以,但是数据太多,而且输入的数据是无序的,用二分查找还得先排序,

 #include<iostream>
#include<cstdio>
#include<algorithm>
#define M 1000010 using namespace std; int a[M]; bool find(int key,int s,int e)
{
int m;
while(s<=e)
{
if(key<a[s]||key>a[e]) return false;
m=(s+e)/;
if(key==a[m]) return true;
else if(key<a[m]) e=m-;
else s=m+;
}
return false;
} int main()
{
int n,m;
scanf("%d%d",&m,&n); int i;
for(i=;i<m;i++) scanf("%d",&a[i]);
sort(a,a+m);
int t;
for(i=;i<n;i++)
{
scanf("%d",&t);
if(find(t,,m-)) printf("YES\n");
else printf("NO\n");
} return ;
}

用map,

 #pragma warning(disable:4786)
#include <iostream>
#include <cstdio>
#include <map>
#include <algorithm>
#include <string>
using namespace std; int main(){
int i;
map<int, int> mp;
int m, n;
scanf("%d%d", &m, &n);
for(i = ; i < m; i++){
int temp;
scanf("%d", &temp);
if(!mp.count(temp))
mp[temp] = ;
mp[temp]++;
}
for(i = ; i < n; i++){
int temp;
scanf("%d", &temp);
if(mp.count(temp))//mp.find(temp) != mp.end()
printf("YES\n");
else
printf("NO\n");
}
return ;
}
05-08 15:49