手写二分,样例对但全WA,求调

P2249 【深基13.例1】查找

Chinami_Nagisa @ 2024-08-15 16:41:29

#include <cstdio>
using namespace std;
int n,m,q;
int a[1000010];
int mid,right,left;
int Find(int x)
{
    right=n-1;
    while(right>left)
    {
        mid=(right+left)/2;
        if(x<=a[mid]) right=mid;    
        else left=mid+1;
    }
    if(a[left]!=x) return -2;
    else return left;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%d",a+i);
    for(int j=0;j<m;j++)
    {
        scanf("%d",&q);
        printf("%d ",Find(q)+1);
    }
    return 0;
}

by liubingrui @ 2024-08-18 11:52:58

你好呀,left没初始化哦,像这种多次询问的题都要初始化的,下次注意就行,这样就AC了

#include <cstdio>
using namespace std;
int n,m,q;
int a[1000010];
int mid,right,left;
int Find(int x)
{
    right=n-1;left=0;
    while(right>left)
    {
        mid=(right+left)/2;
        if(x<=a[mid]) right=mid;    
        else left=mid+1;
    }
    if(a[left]!=x) return -2;
    else return left;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%d",a+i);
    for(int j=0;j<m;j++)
    {
        scanf("%d",&q);
        printf("%d ",Find(q)+1);
    }
    return 0;
}

by liubingrui @ 2024-08-18 11:55:43

@Chinami_Nagisa


by Chinami_Nagisa @ 2024-08-18 15:44:42

@liubingrui 蟹蟹,已收到,下次会注意的^w^,还有你说话真的很友善


by liubingrui @ 2024-08-18 20:18:06

蟹蟹啦没事 >w<


|