#6 TLE

P2249 【深基13.例1】查找

Ginka_ @ 2023-09-03 08:48:06

#include <iostream>
using namespace std;
int n,m,x,ans;
int a[1000100];
int func(int num)
{
    int y=a[num];
    while(a[num]==y)
    {
        num--;
    }
    num++;
    return num;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>n>>m;
    a[0]=-1;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    for(int i=1;i<=m;i++)
    {
        ans=0;
        cin>>x;
        int l=0,r=n+1;
        int mid;
        while(l<=r)
        {
            mid=(l+r)/2;
            if(a[mid]>x)
            {
                r=mid-1;
            }
            else if(a[mid]<x)
            {
                l=mid+1;
            }
            else
            {
                ans=func(mid);
                break;
            }
        }
        if(ans!=0)
            cout<<ans<<" ";
        else
            cout<<"-1 ";
    }
    return 0;
} 

by Squirrel_GZQ @ 2023-09-03 09:40:51

@WonderOfYou 其实这道题用二分写个函数就可以了,func可以不要的


by Ginka_ @ 2023-09-03 09:44:08

@Your_Name 谢谢


|