求教

P2249 【深基13.例1】查找

dqh_0616 @ 2024-12-06 22:55:59

64pts:
结果:wa ac ac ac ac tle

#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[1000007],q;
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 l=1,r=n;
        if(a[1]<=q&&q<=a[n])

            while(l<r){
                int mid=(l+r)/2;
                if(q<a[mid])
                    r=mid-1;
                else if(q>a[mid])
                    l=mid+1;
                else
                    l=r=mid;
            }

        if(l!=r||a[l]!=q)
            printf("-1 ");
        else{
            while(a[l-1]==a[l])l--;
            printf("%d ",l);
        }

    }
    return 0;
}

by tangyiqi @ 2024-12-07 21:21:52

@dqh_0616 用我的AC代码

#include<bits/stdc++.h>
using namespace std;
const int q = 1e6+10;
int a[q],x,n,m;
int left(int x);
int main() {
    int ans;
    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",&x);
        ans = left(x);
        printf("%d ",ans);
    }
    return 0;
}
int left(int x){
    int l = 1,r = n;
    while(l<=r){
        int mid = l+(r-l)/2;
        if(a[mid]<x)l = mid+1;
        else r = mid-1;
    }
    if(l>n || a[l] != x)return -1;
    return l;
}

求关,求加团


by dqh_0616 @ 2024-12-07 21:47:32

@tangyiqi加团了


by tangyiqi @ 2024-12-07 21:49:36

@dqh_0616 OK


|