NYOJ 86--找球号(一)【二分查找】or【set】

23 篇文章 0 订阅

找球号(一)

时间限制: 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

解法一: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值