样例过了,但WA+TLE求助

P2249 【深基13.例1】查找

DougNo1 @ 2024-08-21 10:03:38

代码:

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int a[1000010];
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    for(int i=1;i<=m;i++){
        int c,tmp=0;
        cin>>c;
        int l=1,r=n,mid=(l+r)/2;
        while(l<r){
            if(a[mid]<c) l=mid+1;
            if(a[mid]>c) r=mid-1;
            if(a[mid]==c){
                while(a[mid-1]==a[mid]) mid--;
                tmp=1;
                cout<<mid<<" ";
                break;
            }
            mid=(l+r)/2;
        }
        if(tmp==0) cout<<-1<<" ";
    }
    return 0;
}

提交记录


by Emil_ @ 2024-08-21 10:07:35

@DougNo1

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
const int N=1e6+100;
int n,m,a[N],p;
int main(){
    std::ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }

    for(int i=1;i<=m;i++){
        cin>>p;
        int ans=lower_bound(a+1,a+1+n,p)-a;
        if(p!=a[ans])
            cout<<-1<<" ";
        else
            cout<<ans<<" ";
    }
    return 0;
}

by tangyiqi @ 2024-08-21 11:06:21

@DougNo1
用我的AC代码吧

#include <iostream>
#include <cstdio>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <math.h>
#include <string.h>
#define u using namespace std;
#define ll long long
#define s scanf
#define p printf
#define f for
#define ii int
#define vv void
u
const ii q = 1e6+10;
ii a[q],x,n,m;
ii left(ii x);
ii main() {
    ii ans;
    s("%d%d",&n,&m);
    for(int i = 1;i<=n;i++){
        s("%d",&a[i]);
    }
    for(int i = 1;i<=m;i++){
        s("%d",&x);
        ans = left(x);
        p("%d ",ans);
    }
    return 0;
}
ii left(ii x){
    ii l = 1,r = n;
    while(l<=r){
        ii 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;
}

求关,谢谢,关注后,请加入“https://www.luogu.com.cn/team/86926”团队


|