求助0分

P2249 【深基13.例1】查找

xiongty2024 @ 2023-07-18 12:06:40

#include<iostream>
using namespace std;
int a[100000005];
int kd(){
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-') f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=x*10+c-'0';
        c=getchar();
    }
    return x*f;
}
int main(){
    int n,t,s;
    n=kd();
    t=kd();
    for(int i=0;i<n;i++) a[i]=kd();
    while(t--){
        s=kd();
        int l=0,h=n-1;
        while(l<=h){
            int mid=(l+h)/2;
            if(a[mid]>=s) h=mid-1;
            else l=mid+1;
        }
        if(a[h]==s) printf("%d",h);
        else printf("-1");
        printf("\n");
    }
    return 0;
}

0分,样例全部输出-1,恳请大佬帮助!


by lovely_fcukh @ 2023-07-18 12:12:07

我帮你改了一下A了:

#include<iostream>
using namespace std;
int a[100000005];
int kd(){
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-') f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=x*10+c-'0';
        c=getchar();
    }
    return x*f;
}
int main(){
    int n,t,s;
    n=kd();
    t=kd();
    for(int i=0;i<n;i++) a[i]=kd();
    while(t--){
        s=kd();
        int l=0,h=n-1;
        while(l<h){
            int mid=(l+h)/2;
            if(a[mid]>=s) h=mid;
            else l=mid+1;
        }
        if(a[h]==s) printf("%d ",h+1);
        else printf("-1 ");
    }
    return 0;
}

by lovely_fcukh @ 2023-07-18 12:12:29

@cwfxxty 如果有帮助能不能给个关注谢谢qwq


by xiongty2024 @ 2023-07-18 13:28:59

@lovely_fcukh 关了


|