第一个WA,最后一个TLE

P2249 【深基13.例1】查找

Glocker @ 2024-05-21 17:41:45

写得又臭又长,望大佬帮我改一改

#include <bits/stdc++.h>
using namespace std;
int nl[11451400];
int ml[11451400];
int main(){
    int n,m,c=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>nl[i];
    }
    for(int i=1;i<=m;i++)
    {
        cin>>ml[i];
    }
    int l=1,r=n,mid;
    for(int i=1;i<=m;i++)
    {
        l=1,r=n,c=0;
        while(l<=r)
        {
            mid=(l+r)/2;
            if(nl[mid]==ml[i])
            {
                for(int j=mid;j>=l;j--)
                {
                    if(nl[j-1]<ml[i])
                    {
                        cout<<j<<' ';
                        c=1;
                        break;
                    }
                }
                break;
            }
            else if(nl[mid]<ml[i])
            {
                l=mid+1;
            }
            else if(nl[mid]>ml[i])
            {
                r=mid-1;
            }
        }
        if(c==0)
        {
            cout<<"-1 ";
        }
    }
}

by HEROBRINEH @ 2024-05-21 17:53:19


#include<stdio.h>
const int N = 1e6 + 5;
int n, m;
int q[N];
int main()
{
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++) scanf("%d", &q[i]);
    while (m--)
    {
        int x;
        scanf("%d", &x);

        int l = 1, r = n ;
        while (l < r)
        {
            int mid = l + r>>1;
            if (q[mid] >= x) r = mid; 
            else l = mid + 1;
        }
        if (q[l] != x) printf("-1 ");
        else printf("%d ", l);
    }
    return 0;
}

|