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

题目链接: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;
}
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页