样例过了上谷全wa

P2249 【深基13.例1】查找

xiongmy123 @ 2023-06-10 14:29:18

代码如下

#include <bits/stdc++.h>
using namespace std;

int n,m;

int ef(int a[],int x){
    int l=0,r=m-1,mid=(l+r)/2;
    while(l<r){
        int mid=(l+r)/2;
        if(a[mid]==x)
           return mid;
        else if(a[mid]<x){
            l=mid+1;
        }
        else if(a[mid]>x)
            r=mid;
    }
    return -1;
}

int main(){
    cin>>n>>m;
    int a1[n],a2[m];
    for(int i=0;i<n;i++){
        cin>>a1[i];
    }
    for(int i=0;i<m;i++){
        cin>>a2[i];
    }
    for(int i=0;i<m;i++){
        int x=ef(a1,a2[i]);
        if(x==-1)
          cout<<-1<<" ";
        else{
           while(a1[x]==a2[i])
             x--;
           cout<<x+2<<" ";
        }
    }
  return 0;
}

by wang1h @ 2023-06-10 15:20:37

#include <bits/stdc++.h>
using namespace std;

int n,m;

int a1[1000010],a2[100010];//大数组开在main外,不要用变量做数组长度

int ef(int x){//ef这样写
    int l=0,r=n-1,mid;
    while(l<r){
        mid=l+(r-l)/2;
        if (a1[mid]>=x)
            r=mid;
        else
            l=mid+1;
    }
    if (a1[l]==x) return l+1;
    return -1;
}
int main(){
    cin>>n>>m;

    for(int i=0;i<n;i++){
        cin>>a1[i];
    }
    for(int i=0;i<m;i++){
        cin>>a2[i];
    }
    for(int i=0;i<m;i++){
        int x=ef(a2[i]);
        if(x==-1)
          cout<<-1<<" ";
        else{
            //这的while很迷惑
           cout<<x<<" ";
        }
    }
  return 0;
}

关注 @ wang1hao 谢谢喵~


by wang1h @ 2023-06-10 15:21:16

@xiongmy123


by wang1h @ 2023-06-10 15:48:36

@xiongmy123

回我啊啊啊啊,码了好久的字(也才5分钟


by xiongmy123 @ 2023-06-10 19:29:30

谢谢大佬


by xiongmy123 @ 2023-06-10 19:30:10

@wang1h


|