求简单答案

P2249 【深基13.例1】查找

linlinknock @ 2024-12-19 20:10:01

求一个简单的解答,不知道为什么全是wa

#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 1e6 + 8;
int a[maxn];
int find(int l, int r, int x) {
    while (l < r) {
        int mid = (l + r) >> 1;
        if (a[mid] < x) {
            l = mid + 1;
        }
        if (a[mid] >= x) {
            r = mid - 1;
        }
    }
    if (a[r] == x) {
        return r;
    }
    return -1;
}
int main() {
    int n, m, x, ans[maxn];
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 1; i <= m; i++) {
        cin >> x;
        ans[i] = find(1, n, x);
    }
    for (int i = 1; i <= m; i++) {
        cout << ans[i] << endl;
    }
    return 0;
}

by LionBlaze @ 2024-12-19 20:24:00

@linlinknock 答:写错了。


by LionBlaze @ 2024-12-19 20:24:10

够简单吗


by LiujunjiaNC @ 2024-12-19 20:27:24

@linlinknock

#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 1e6 + 8;
int a[maxn], ans[maxn];
int find(int l, int r, int x) {
    while (l < r) {
        int mid = (l + r) >> 1;
        if (a[mid] < x) {
            l = mid + 1;
        }
        if (a[mid] >= x) {
            r = mid;
        }
    }
    if (a[r] == x) {
        return r;
    }
    return -1;
}
int main() {
    int n, m, x;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 1; i <= m; i++) {
        cin >> x;
        ans[i] = find(1, n, x);
    }
    for (int i = 1; i <= m; i++) {
        cout << ans[i] << " ";
    }
    return 0;
}

by linlinknock @ 2024-12-19 22:10:46

谢,已关


|