Cod sursa(job #1891269)

Utilizator GeoeyMexicanuBadita George GeoeyMexicanu Data 23 februarie 2017 21:04:32
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#define N 100010

using namespace std;

ifstream f("cautbin.in");
ofstream g("cautbin.out");

int v[N],i,j,n,m;
int bcaut(int s,int d,int x)
{
    int i,step;
    for(step=1;step<=d;step<<=1);
    for(i=s-1;step;step>>=1)
    {
        if(i+step<=d && v[i+step]<=x)
            i+=step;
    }
    return i;
}
int bcaut2(int s,int d,int x)
{
    int i,step;
    for(step=1;step<=d;step<<=1);
    for(i=d;step;step>>=1)
    {
        if(i-step>0 && v[i-step]>=x)
            i=i-step;
    }
    return i;
}
int main()
{
    int x,y;
    f>>n;
    for(i=1;i<=n;i++)
        f>>v[i];
    f>>m;
    int poz;
    while(m!=0)
    {
        f>>x>>y;
        if(x==0 || x==1)
        {
            poz=bcaut(1,n,y);
            if(x==0 && v[poz]!=y)
                g<<-1<<"\n";
            else
                g<<poz<<"\n";
        }
        else
        {
            g<<bcaut2(1,n,y)<<"\n";
        }
        m--;
    }
}