感谢各位大佬帮帮我这个 0pts 的蒟蒻吧~

P2249 【深基13.例1】查找

liuzhouyang @ 2024-10-03 17:56:52

废话不多说,上代码:

(对啦,我已经会 STL 做法啦。。)

#include<bits/stdc++.h>
#define int long long
#define float double
#define N 1000005
using namespace std;
int n,m,a[N],q,l,r,mid;
signed main()
{
    ios::sync_with_stdio(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    while(m--)
    {
        cin>>q;
        l=1;
        r=n;
        while(l+1<r)
        {
            mid=(l+r)/2;
            if(a[mid]>=q)
            {
                r=mid-1;
            }
            else
            {
                l=mid+1;
            }
        }
        if(a[r]==q)
        {
            cout<<r<<' ';
        }
        else if(a[l]==q)
        {
            cout<<l<<' ';
        }
        else
        {
            cout<<-1<<' ';
        }
    }
}

by liuzhouyang @ 2024-10-03 17:58:33

我的代码有点长可能是因为没压行吧QWQ。。。


by _LFC_ @ 2024-10-03 17:59:41

@liuzhouyang

#include<bits/stdc++.h>
#define int long long
#define float double
#define N 1000005
using namespace std;
int n,m,a[N],q,l,r,mid;
signed main()
{
    ios::sync_with_stdio(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    while(m--)
    {
        cin>>q;
        l=1;
        r=n;
        while(l<r)
        {
            mid=(l+r)/2;
            if(a[mid]>=q)
            {
                r=mid;
            }
            else
            {
                l=mid+1;
            }
        }
        if(a[r]==q)
        {
            cout<<r<<' ';
        }
        else if(a[l]==q)
        {
            cout<<l<<' ';
        }
        else
        {
            cout<<-1<<' ';
        }
    }
}

by liuzhouyang @ 2024-10-03 18:00:31

@LFC 秒回呀大哥。


by liuzhouyang @ 2024-10-03 18:02:02

@LFC 大佬我AC了蟹蟹你~~~


by liuzhouyang @ 2024-10-03 18:03:21

@LFC 大佬我关注一下你好吧!!!


by _LFC_ @ 2024-10-03 19:12:43

@liuzhouyang 其实我也不知道是什么原理(逃


|