#1WA,#5TLE,求助orz!!!

P2249 【深基13.例1】查找

Calarence4 @ 2023-11-10 19:38:54

#include <bits/stdc++.h>
using namespace std;
int n, q;
int num[(int)1e6];
int main() {
    scanf("%d%d", &n, &q);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &num[i]);
    }
    for (; q-- != 0;) {
        int l = 1, r = n, m = (l + r) / 2;
        int target;
        scanf("%d", &target);
        bool flag = false;
        while (r >= l) {
            if (target == num[m]) {
                flag = true;
                while (target == num[m - 1]) {
                    m--;
                }
                break;
            } else if (target < num[m]) {
                r = m - 1;
                m = (l + r) / 2;
            } else {
                l = m + 1;
                m = (l + r) / 2;
            }
        }
        if (flag == false) {
            printf("-1 ");
        } else {
            printf("%d ", m);
        }
    }
    return 0;
}

|