0分求调

P2249 【深基13.例1】查找

Redmist @ 2024-10-03 10:40:54

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,a[1000010];
void search(int l,int r,int x){
    while(l<=r){
        int mid=l+(r-l)/2;
        if(a[mid]>=x){
            r=mid-1;
        }if(a[mid]<x){
            l=mid+1;
        }
    }if(a[l]==x){
        cout<<l<<" ";
        return;
    }else{
        cout<<"-1"<<" ";
    }
    return;
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    scanf("%d",&n);
    scanf("%d",&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=m;i++){
        int x;
        cin>>x;
        search(0,n,x);
    }
    return 0;
}

by Wmz1220 @ 2024-10-03 10:52:23

@Redmist

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,a[1000010];
void search(int l,int r,int x)
{
    while(l < r)//第一,你的二分为左闭右开的区间,所以得是l < r
    {
        int mid = l + (r - l) / 2;
        if (a[mid] >= x)
            r = mid;
        else l = mid + 1;
    }

    if(a[l]==x)
    {
        cout<<l<<" ";
        return;
    }
    else
    {
        cout<<"-1"<<" ";
    }
    return;
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);//第二,一旦你用了这两行,你这不能混用scanf和printf
    cin >> n;
    cin >> m;
    for(int i=1;i<=n;i++){
        cin >> a[i];
    }
    for(int i=1;i<=m;i++){
        int x;
        cin>>x;
        search(1, n, x);
    }
    return 0;
}

帮你调好了,求关


|