Aizu ITP2_6_A 二分

For a given sequence A = { a 0 , a 1 , . . . , a n 1 } A = \{a_0, a_1, ..., a_{n-1}\} which is sorted by ascending order, find a specific value k k given as a query.

Input
The input is given in the following format.

n n
a 0    a 1    , . . . ,    a n 1 a_0 \; a_1 \; ,..., \; a_{n-1}
q q
k 1 k_1
k 2 k_2
:
k q k_q
The number of elements n n and each element a i a_i are given in the first line and the second line respectively. In the third line, the number of queries q q is given and the following q q lines, q q integers k i k_i are given as queries.

Output
For each query, print 1 if any element in A A is equivalent to k k , and 0 otherwise.

Constraints
1 < n < 100 , 000 1 < n < 100,000
1 < q < 200 , 000 1< q < 200,000
0 < a 0 < a 1 < . . . < a n 1 < 1 , 000 , 000 , 000 0 < a_0 < a_1 < ... < a_{n-1} < 1,000,000,000
0 < k i < 1 , 000 , 000 , 000 0 < k_i < 1,000,000,000
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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43849505/article/details/87373757