求助#6 TLE

P2249 【深基13.例1】查找

dazahui @ 2023-10-10 17:41:07

#include <bits/stdc++.h>

using namespace std;

void find(double x,double a[],int n)
{
    int ret=-2;
    int first=0,last=n-1,mid;
    while(first<=last)
    {
        mid =first+((last-first)>>1);
        if (a[mid]<x)
        {
            first=mid+1;
        }else if(a[mid]>x)
        {
            last=mid-1;
        }else if (a[mid]==x)
        {
            ret=mid;
            for (int i=mid;a[i]==x;i--)
            {
                ret=i;
            }
            break;
        }
    }
    cout<<ret+1<<" ";
}

inline double DoubleRead(){
    long long s = 0, w = 1, k = 0, n = 0, m = 0;
    char ch = getchar(); 
    while(ch < '0' || ch > '9'){
        if(ch == '-') w = -1;
        ch = getchar();
    }
    while((ch >= '0' && ch <= '9') || ch == '.'){
        if (ch == '.')
            n = 1;
        else if (n == 0)
            s = s * 10 + ch - '0';
           else k = k * 10 + ch - '0', m++;
        ch = getchar();
    }
    return (pow(0.1, m) * k + s) * w;
}

int main()
{
    int n,m;
    cin>>n>>m;
    double data[n];
    double search[m];
    for (int i=0;i<n;i++)
    {
        data[i]=DoubleRead();
    }
    for (int i=0;i<m;i++)
    {
        cin>>search[i];
    }
    for (int i=0;i<m;i++)
    {
        find(search[i],data,n);
    }
    return 0;
}

求助,想知道哪里可以加快


by hq13034861770 @ 2023-10-28 15:11:25

你用了二分查找法吗?


|