零分求调

P2249 【深基13.例1】查找

GankoT @ 2024-08-27 01:10:45

#include<iostream>
using namespace std;
const int maxn=1e6+10;
long long a[maxn];
int main(){
    int n,m;
    cin >> n >> m;
    int j = 1;
    for(int i = 0;i < n;i++){
        cin >> a[j];
        if(j==1||a[j]!=a[j-1]){
            j++;
        }
    }
    for(int i = 0;i < m;i++){
        int x;
        cin >> x;
        int l = 1,r=j-1;
        while(l<=r){
            int mid = l+(r-l)/2;
            if(a[mid]==x){
                cout << mid ;
                cout << " " ;
                break;
            }
            else if(a[mid]>x){
                r = mid-1;
            }
            else{
                l = mid+1;
            }
        }
        if(l>r){
                cout << -1 ;
        }
    }
    return 0;
}

by mengfancheng @ 2024-08-27 07:53:28

#include<bits/stdc++.h>
using namespace std;
int main() {
    int n,k;
    cin>>n>>k;
    int x[n+1]={-10};
    for(int i=1;i<=n;i++){
        cin>>x[i];
    }
    for(int mn=0;mn<k;mn++){
        int xx;
        cin>>xx;
        int l=1,r=n; 
        while(l<=r){
            int nn=(l+r)/2;
            if(xx<=x[nn]){
                r=nn-1;
            }else{
                l=nn+1;
            }
        }
        if(x[l]==xx){
            cout<<l<<" ";
        }else{
            cout<<-1<<" ";
        }
    }
}

求关


by adsd45666 @ 2024-08-27 07:58:41

错误有点多,一个个来

  1. j的作用看代码应该是去重的,但去重会导致后续的查询错误

  2. 对于此题的题目要求,输出第一次出现的编号,应为结束时L的位置,你的代码会输出mid的位置

  3. 以及二分有点小错误

AC code:

int n,m;
    cin >> n >> m;
    // int j = 1;
    for(int i = 1;i <= n;i++){
        cin >> a[i];
        // if(j==1||a[j]!=a[j-1]){
        //     j++;
        // }
    }
    for(int i =1;i <= m;i++){
        int x;
        cin >> x;
        int l = 1,r=n;
        while(l<r){
            int mid = l+(r-l)/2;
            if(a[mid]>=x)
                r = mid;
            else
                l = mid+1;
        }
        if(a[l]==x) cout<<l<<" ";
        else        cout<<"-1"<<" ";
        // if(l>r){
        //      cout << -1 ;
        // }
    }

|