【整数二分】

数的范围

#include
using namespace std;
const int N = 100000 + 11;

int n;
int q;
int a[N];

int key;

int main(){
    cin>>n>>q;
    for(int i=0;i<n;i++)
        cin>>a[i];
    while(q--){
        cin>>key;
        //先去找左(大于等于)再去找右(小于等于)
        //大于等于就是(找左端点,对应模板的右区间)
        //小于等于就是(找右端点,对应模板的左区间)
        int l = 0;
        int r = n-1;
        while(l<r){
            //mid在while循环中定义
            int mid = (l+r)>>1;
            if(a[mid]>=key) r = mid;
            else    l = mid+1;
        }
        if(a[l]!=key)
            cout<<"-1 -1"<<endl;
        else{
            cout<<l<<" ";
            l = 0;
            r = n-1;
            while(l<r){
                int mid = (l+r+1)>>1;
                if(a[mid]<=key) l = mid;
                else    r = mid-1;
            }
            cout<<l<<endl;
        }
    }
    return 0;
}

你可能感兴趣的:(algorithm,算法)