Cod sursa(job #2549695)

Utilizator sipdavSipos David Oliver sipdav Data 17 februarie 2020 21:57:50
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>

using namespace std;

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

const int dim = 100001;

int n, m, c, x, v[dim], p;

int cauta(int val)
{
    int st = 1;
    int poz = 0;
    for(st;st <= n;st <<= 1);
    for(poz; st; st >>= 1)
    {
        if(poz + st <= n && v[poz + st] <= val)
            poz += st;
    }
    return poz;
}

int revcauta(int val)
{
    int st = 1;
    int poz = n;
    for(st; st <= n;st <<= 1);
    for(poz; st; st >>= 1)
    {
        if(poz - st > 0 && v[poz - st] >= x)
            poz -= st;
    }
    return poz;
}

int main()
{
    in>>n;
    for(int i = 1;i <= n;i++)
        in>>v[i];
    in>>m;
    for(int i = 1;i <= m;i++)
    {
        in>>c>>x;
        if(c == 0)
        {
            p = cauta(x);
            if(v[p] == x)
                out<<p<<'\n';
            else
                out<<-1<<'\n';
        }
        if(c == 1)
            out<<cauta(x)<<'\n';
        if(c == 2)
            out<<revcauta(x)<<'\n';
    }
    return 0;
}