Cod sursa(job #2074324)

Utilizator cristianursacheCristian Ursache cristianursache Data 24 noiembrie 2017 14:38:04
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>

using namespace std;

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

const int L = 16;

int v[100001];

int n;

int caut0 (int x)
{
    int r = 0, pas = 1 << L;
    while (pas != 0)
    {
        if (r + pas <= n && v[r + pas] <= x)
            r += pas;
        pas /= 2;
    }
    if (v[r] != x)
        r = -1;
    return r;
}

int caut1 (int x)
{
    int r = 0, pas = 1 << L;
    while (pas != 0)
    {
        if (r + pas <= n && v[r + pas] <= x)
            r += pas;
        pas /= 2;
    }
    return r;
}

int caut2 (int x)
{
    int r = 0, pas = 1 << L;
    while (pas != 0)
    {
        if (r + pas <= n && v[r + pas] < x)
            r += pas;
        pas /= 2;
    }
    r ++;
    return r;
}

int main()
{
    int nr, a, x;
    in >> n;
    for (int i = 1; i <= n; i++)
        in >> v[i];
    in >> nr;
    for (int i = 1; i <= nr; i++)
    {
        in >> a >> x;
        if (a == 0)
            out << caut0 (x);
        if (a == 1)
            out << caut1 (x);
        if (a == 2)
            out << caut2 (x);
        out << '\n';
    }
    return 0;
}