为什么二分RE了

P2249 【深基13.例1】查找

violet1123 @ 2024-10-13 17:47:00

#include<iostream>

using namespace std;

const int N = 100010;
int a[N];

int main()
{
    int n, m,q;
    cin >> n >> m;
    for (int i = 0; i < n; i++)
        cin >> a[i];

    for (int i = 0; i < m; i++)
    {
        cin >> q;
        int x = 0, y = n  - 1;
        while (x < y )
            {
                int mid = x + y >> 1;
                if (a[mid] >= q) y = mid;
                else x = mid + 1;
            }
        if (a[x] == q) cout << x + 1<< ' ';
        else cout << "-1 ";
    }
    return 0;
}

by Down_syndrome @ 2024-10-13 17:53:47

@violet1123 数组开少了一个零


by ikun_555 @ 2024-10-13 17:54:29

啊对对对


by lijichuan @ 2024-10-13 17:54:29

21行 改为(x+y)>>1而且mid最好在外面定义,不然每次都会重新定义一次

#include<iostream>

using namespace std;

const int N = 1000005;
int a[N];

int main()
{
    int n, m,q;
    cin >> n >> m;
    for (int i = 0; i < n; i++)
        cin >> a[i];

    for (int i = 0; i < m; i++)
    {
        cin >> q;
        int x = 0, y = n  - 1,mid;
        while (x < y )
            {
                mid = (x+y) /2;
                if (a[mid] >= q) y = mid;
                else x = mid + 1;
            }
        if (a[x] == q) cout << x + 1<< ' ';
        else cout << "-1 ";
    }
    return 0;
}

|