洛谷 P2249 【深基13.例1】查詢

百轉千迴夢醒十分發表於2020-09-27

題目連結:https://www.luogu.com.cn/problem/P2249


本題是左二分的簡單應用。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1e6 + 10;

int n, m;
int a[N];

int main(){
    cin >> n >> m;
    for (int i = 0; i < n; i ++ ) cin >> a[i];
    
    while (m -- ){
        int x; cin >> 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 << "-1" << ' ';
        else cout << l + 1<< ' ';
    }
    
    return 0;
}

相關文章