满屏WA

P2249 【深基13.例1】查找

wym_2012 @ 2023-07-10 10:45:21

代码如下

#include<bits/stdc++.h>
using namespace std;
int n,m,a[1000009],q;
int find(int x)
{
    int l=1,r=n;
    while(l<r)
    {
        int mid=(l+r)/2;
        if(a[mid]>=x)
            r=mid-1;
        else
            l=mid+1;
    }
    if(a[l]==x)
        return l;
    return -1;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    for(int i=1;i<=m;i++)
    {
        scanf("%d",&q);
        int ans=find(q);
        printf("%d ",ans);
    }
    return 0;
} 

样例还是一片祥和,上洛谷全WA
大佬帮忙看看


by ty127sb @ 2023-07-10 10:50:44

l<=r


by wym_2012 @ 2023-07-10 11:12:37

@ty12345678 谢谢大佬


by _Adolf_Hitler_ @ 2023-07-10 11:22:13

#include <bits/stdc++.h>
using namespace std;
const long long MAXN=1e7+10;
int a[MAXN],n,k,m,t;
int finds(int t)
{
    int i=1;
    int j=n;
    int mid;
    while(i<=j)
        {
            mid=(i+j+1)/2;
            if(a[mid]>=t)
                j=mid-1;
            else
                i=mid+1;
        }
    if(a[i]==t)
        return i;
    return -1;
}
int main()
{
    cin>>n>>m;
    for(int i=1; i<=n; i++)
        cin>>a[i];
//  sort(a+1,a+n+1);
    for(int i=1; i<=m; i++)
        cin>>t,cout<<finds(t)<<" ";
    return 0;
}

|