#1WA #6TLE 样例也能过

P2249 【深基13.例1】查找

Alfa_Romeo_F1 @ 2023-12-12 16:25:56

#include<bits/stdc++.h>
using namespace std;
int a[1000003];
int find(int t[],int a,int l,int r){
    int mid=(l+r)/2;
    if(abs(l-r)<=1&&t[l]!=a&&t[r]!=a) return -1;
    if(t[mid]>a){
        return find(t,a,l,mid-1);
    }
    else if(t[mid]<a){
        return find(t,a,mid+1,r);
    }
    else {
        if(t[mid]==a) {
            while(t[mid-1]>=a)mid--;
            return mid;
        }

    }

}

int main(){
    int n,m;
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=m;i++){
        int tmp;
        scanf("%d",&tmp);
        if(tmp==0&&a[1]==0){
            cout<<1;
            continue;
        }
        int ans=find(a,tmp,1,n);
        printf("%d ",ans);
    }
    return 0;
}

|