For a given sequence which is sorted by ascending order, find a specific value given as a query.
Input
The input is given in the following format.
:
The number of elements
and each element
are given in the first line and the second line respectively. In the third line, the number of queries
is given and the following
lines,
integers
are given as queries.
Output
For each query, print 1 if any element in
is equivalent to
, and 0 otherwise.
Constraints
Sample Input 1
4
1 2 2 4
3
2
3
5
Sample Output 1
1
0
0
二分查找的模版题,写法类似于线段树里的查询函数,注意一下递归的终点即可。
AC代码:
#include<iostream>
#include<stdio.h>
long long int num[100005];
using namespace std;
void fun(int l,int r,long long int tar)
{
if(r<l)
{
cout<<"0"<<endl;
return;
}
int mid=(l+r)/2;
if(num[mid]==tar)
{
cout<<"1"<<endl;
return;
}
if(num[mid]<tar) fun(mid+1,r,tar);
else fun(l,mid-1,tar);
}
int main()
{
int n1,n2;
cin>>n1;
for(int i=0;i<n1;i++)
cin>>num[i];
cin>>n2;
while(n2--)
{
int temp;
cin>>temp;
fun(0,n1-1,temp);
}
return 0;
}