Cod sursa(job #1506555)

Utilizator RodoetTeodor Darie Rodoet Data 20 octombrie 2015 19:45:35
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
ifstream in("cautbin.in");
ofstream out("cautbin.out");
long n,m;
long long v[100010];
bool ok(long poz,long long cautat)
{
    if (poz<0 || poz>=n) return 0;
    if (v[poz] <= cautat) return 1;
    return 0;
}

long cautbin (long long cautat, bool &gasit)
{
    long step = 1;
    while(step<n)
    {
        step*=2;    }
    long poz=0;
    while (step>0)
    {
        if (ok(poz+step,cautat))
        {
            poz+=step;
        }
        step /= 2;
    }
    if (v[poz]==cautat) gasit=1;
    return poz;
}

void roteste (long long copie[100010])
{
    int i,j=0;
    for (i=n-1;i>=0;i--)
    {
        copie[j++]=v[i];
    }
}
int main()
{
    in>>n;
    bool gasit;
    long i,x;
    long long cautat;
    long long inversat[100010];
    roteste(inversat);
    for (i=0;i<n;i++)
    {
        in>>v[i];
    }
    in>>m;
    for (i=0;i<m;i++)
    {
        gasit=0;
        in>>x>>cautat;
        if (x==0)
        {
            x=cautbin(cautat,gasit)+1;
            if (gasit) out<<x<<endl;
            else out<<-1;
        }
        if (x==1)
        {
            out<<cautbin(cautat,gasit)+1;
        }
        if (x==2)
        {
            out<<n-cautbin(cautat,gasit);
        }
    }
    return 0;
}