请大佬看看哪里出错了 #1,#4,#5TLE #2,#3,#6AC

P2249 【深基13.例1】查找

jasonlixuran @ 2024-04-07 17:59:26

#include<bits/stdc++.h>
using namespace std;
int a[10000010];
int n;
int b[10000010];
int s(int x)
{
    int l = 0,r=n-1;
    while(l<=r)
    {
        int mid = (l+r)/2;
        if(a[mid]>x)
        {
            r = mid-1;
        }
        else if(a[mid]<x)
        {
            l = mid+1;
        }
        else 
        {
            for(int i = 0; i<mid; i++)
            {
                if(a[i]==x)
                return i+1;
            }
            return mid+1;
        }
    }
    return -1;
}
int main()
{
    int m;
    cin>>n>>m;
    for(int i = 0; i<n; i++)
    {
        cin>>a[i];
    }
    for(int i = 0; i<m; i++)
    {
        cin>>b[i];
    }
    for(int i = 0; i<m; i++)
    {
        b[i]=s(b[i]);
    }
    for(int i = 0; i<m; i++)
    {
        cout<<b[i]<<" ";
    }
}

by LRRabcd @ 2024-04-07 18:25:59

#include<iostream>
using namespace std;
int a[1000005],n,m;
int find(int x){
    int l=1,r=n,ans=-1;
    while(l<=r){
        int mid=(l+r)/2;
        if(x==a[mid]){
            ans=mid;
        }
        if(a[mid]<x){
            l=mid+1;
        }else{
            r=mid-1;
        }
    }
    return ans;
} 
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    for(int i=1;i<=m;i++){
        int x;
        cin>>x;
        cout<<find(x)<<" ";
    }
    return 0;
}

by LRRabcd @ 2024-04-07 18:36:02

#include<iostream>
using namespace std;
int a[1000005],n,m;
int find(int x){
    int l=0,r=n+1;
    while(l+1<r){
        int mid=(l+r)/2;
        if(a[mid]>=x){
            r=mid;
        }else{
            l=mid;
        }
    }
    if(a[r]==x){
        return r;
    }else{
        return -1; 
    } 
} 
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    a[0]=-1e9;
    a[n+1]=1e9;
    for(int i=1;i<=m;i++){
        int x;
        cin>>x;
        cout<<find(x)<<" ";
    }
    return 0;
}

by jasonlixuran @ 2024-04-07 19:11:17

@20121028LRR 谢谢,已关


|