NYOJ 86 找球号(一)

链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=86

用数组标记法爆内存,暴力搜索超时....有一种方法是 快排+二分查找.可以过,但是有点慢..

 
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int ball[1000005];
int main()
{
	bool binsearch(int n,int key);
	int m,n;
	int tem;
	int i;
	scanf("%d%d",&m,&n);
	for (i=0;i<m;i++)
		scanf("%d",&ball[i]);

	sort(ball,ball+m);
	for (i=0;i<n;i++)
	{
		scanf("%d",&tem);

		if(binsearch(m,tem))
			printf("YES
");
		else
			printf("NO
");
	}
	return 0;
}

bool binsearch(int n,int key)					//在ball[]中查找key,数组长度为n
{
	int low=0,high=n-1;
	int mid;
	
	while(low<=high)
	{
		mid=low+(high-low)/2;

		if(ball[mid]==key)
			return true;
		if(ball[mid]<key)
			low=mid+1;
		else
			high=mid-1;

	}

	return false;
}        


 用set容器:

#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
int main()
{
	int n,m;
	int i,a;
	
	set<int>ss;
	scanf("%d%d",&n,&m);
	while(n--)
	{
		scanf("%d",&a);
		ss.insert(a);
	}
	for (i=0;i<m;i++)
	{
		scanf("%d",&a);
		if(ss.find(a)!=ss.end())
			printf("YES
");
		else
			printf("NO
");
	}
	return 0;
}


 

原文地址:https://www.cnblogs.com/frankM/p/4399535.html