当前位置:网站首页>【acwing】789. Range of numbers (binary basis)

【acwing】789. Range of numbers (binary basis)

2022-07-07 10:15:00 percation

Through the tunnel
 Insert picture description here


#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int a[N];
int n,q;

int main(){
    
    scanf("%d%d",&n,&q);
    for(int i = 0; i < n; i++){
    
        scanf("%d",&a[i]);
    }
    while(q--){
    
        int x;
        scanf("%d",&x);
        int l = 0, r = n - 1;
        while(l < r){
    
            int mid = l + r >> 1;
            if(a[mid] >= x){
    
                r = mid;
            }
            else{
    
                l = mid + 1;
            }
        }
        if(a[l] == x) cout << l <<" ";// Whether the element pointed to by the current pointer is equal to the queried element , If equal to, it means that the element exists , Returns the left endpoint of the element 
        else{
    
            cout << "-1 -1" << endl;
            continue;
        }
        l = 0, r = n - 1;// Determine the position of the right endpoint of the queried element 
        while(l < r){
    
            int mid = (l + r + 1)>> 1;
            if(a[mid] <= x){
    
                l = mid;
            }
            else{
    
                r = mid - 1;
            }
        }
        cout << l << endl;
        
    }
    return 0;
}
原网站

版权声明
本文为[percation]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070746060554.html