求调

P2249 【深基13.例1】查找

LYQ_666 @ 2024-07-14 16:13:16

#include <iostream> 
using namespace std;
long long a[100002],b,w[100002]; 
int main()
{
    int n,m,mid,l,r,i,q=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        w[i]=-1;
    }
    for(int i=1;i<=m;i++)
    {
        cin>>b; 
        l=1;r=n;q=0;
        while(l<=r)
        {
            mid=(l+r)/2;        
            if(b==a[mid]) 
            {
                w[i]=mid;
                break;
            }
            else if(a[mid]>b) r=mid-1;
            else if(a[mid]<b) l=mid+1;
        }
    }
    for(int i=1;i<=m;i++)
    {
        if(w[i]==-1) cout<<"-1"<<" ";
        else cout<<w[i]<<" ";
    }
    return 0;
}

by caoshuchen @ 2024-07-14 16:49:42

a数组开小了

二分有问题,查的不是最靠前的

#include <bits/stdc++.h> 
using namespace std;

long long a[1000005], w[1000005]; 

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i];
        w[i] = -1;
    }
    for (int i = 1, b; i <= m; i++)
    {
        cin >> b; 
        int l = 0, r = n;
        while (r - l > 1) {
            int mid = (l + r) / 2;          
            if (b <= a[mid])
                r = mid;
            else
                l = mid;
        }
        if (b == a[l + 1])
            w[i] = l + 1;
    }
    for (int i = 1; i <= m; i++)
        cout << w[i] << " ";
    return 0;
}

by LYQ_666 @ 2024-07-15 12:34:20

@caoshuchen 谢谢


|