蒜头君手上有个长度为 nn 的数组 AA。由于数组实在太大了,所以蒜头君也不知道数组里面有什么数字,所以蒜头君会经常询问整数 xx 是否在数组 AA 中。
输入格式
第一行输入两个整数 nn 和 mm,分别表示数组的长度和查询的次数。
接下来一行有 nn 个整数 a_iai。
接下来 mm 行,每行有 11 个整数 xx,表示蒜头君询问的整数。
输出格式
对于每次查询,如果可以找到,输出"YES"
,否则输出"NO"
。
数据范围
1 \le n, m \le 10^5, 0 \le x \le 10^61≤n,m≤105,0≤x≤106。
Sample Input
10 5 1 1 1 2 3 5 5 7 8 9 0 1 4 9 10
Sample Output
NO YES NO YES NO
这道题需要使用二分法,先排序,再二分,固代码如下
#include <stdio.h>
void quicksort(int left,int right,int str[]) //快速排序
{
int i,j,temp,t;
if(left>right)
return;
temp=str[left];
i=left;
j=right;
while(i!=j)
{
while(str[j]>=temp&&j>i)
{
j--;
}
while(str[i]<=temp&&j>i)
{
i++;
}
if(i<j)
{
t=str[i];
str[i]=str[j];
str[j]=t;
}
}
str[left]=str[i];
str[i]=temp;
quicksort(left,i-1,str);
quicksort(i+1,right,str);
return;
}
int Bin_Search(int *str,int cnt, int target) //二分法
{
int first=1,last=cnt,mid;
while(first<=last)
{
mid=(first+last)/2;
if(str[mid]>target)
{
last=mid-1;
}
else if(str[mid]<target)
{
first=mid+1;
}
else
return 1;
}
return 0;
}
int main(void)
{
int n,m,i,j,flag;
scanf("%d%d",&n,&m);
int str[n];
for(i=1;i<=n;i++)
{
scanf("%d",&str[i]);
}
quicksort(1,n,str);
while(m--)
{
scanf("%d",&j);
flag=Bin_Search(str,n,j);
if(flag==1) printf("YES\n");
else printf("NO\n");
}
return 0;
}