Aizu ITP2_6_A(二分模板)

Posted yzhhh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Aizu ITP2_6_A(二分模板)相关的知识,希望对你有一定的参考价值。

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

Input

The input is given in the following format.

$n$
$a_0 ; a_1 ; ,..., ; a_{n-1}$
$q$
$k_1$
$k_2$
:
$k_q$

The number of elements $n$ and each element $a_i$ are given in the first line and the second line respectively. In the third line, the number of queries $q$ is given and the following $q$ lines, $q$ integers $k_i$ are given as queries.

Output

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

Constraints

  • $1 leq n leq 100,000$
  • $1 leq q leq 200,000$
  • $0 leq a_0 leq a_1 leq ... leq a_{n-1} leq 1,000,000,000$
  • $0 leq k_i leq 1,000,000,000$

Sample Input 1

4
1 2 2 4
3
2
3
5

Sample Output 1

1
0
0

题意:如果序列中有元素k则输出1,否则输出0。

思路:二分模板题。见代码。

疑惑:可能是这个题测试数据比较水,不排序也能过。


 

 1 #include<iostream>
 2 #include<algorithm> 
 3 using namespace std;
 4 int N;
 5 long long a[100005];
 6  
 7 int find(long long x,int l,int r){
 8     int m=(r+l)>>1;
 9     while(r>=l){
10         if(x==a[m]) return 1;
11         else if(x<a[m]) r=m-1;
12         else  l=m+1;
13                 
14         m=(r+l+1)>>1;
15     }
16 return 0;
17 }
18 
19 int main(){
20     int Q;
21     long long x;
22     
23     cin>>N;
24     for(int i=0;i<N;i++)
25         cin>>a[i];
26     sort(a,a+N);    
27     cin>>Q;
28     while(Q--){
29         cin>>x;
30         cout<<find(x,0,N-1)<<endl;
31     }     
32     return 0;
33 }

 

以上是关于Aizu ITP2_6_A(二分模板)的主要内容,如果未能解决你的问题,请参考以下文章

[Aizu] ITP2_9_A~D: Set Operation

[Aizu] ITP2_11_A~D: 子集的枚举系列

[Aizu] ITP2_8_A: Map: Search

Exhaustive Serch ( Aizu - ALDS1_5_A )

Stack,( Aizu - ALDS1_3_A)

有根树的表达 Aizu - ALDS1_7_A: Rooted Trees