1. 程式人生 > >Aizu ITP2_6_A(二分模板)

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 }