Cod sursa(job #2607941)

Utilizator Silviu.Stancioiu@gmail.comSilviu Stancioiu [email protected] Data 30 aprilie 2020 13:54:33
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");

    int n;
    fin >> n;
    uint32_t* v;
    v = new uint32_t[n];
    uint32_t mx = 1;
    for (int i = 0; i < n; i++)
    {
        fin >> v[i];
        mx = max(mx, v[i]);
    }

    int ix = 0;
    for (int i = 0; i < 32; i++)
        if (mx >> i & 1)
            ix = i;
    mx = 1 << (ix + 1);

    int m;
    fin >> m;

    for (int i = 0; i < m; i++)
    {
        uint32_t task, x;
        fin >> task >> x;

        int sol = 0;
        if (task == 2)
            sol = n - 1;

        for (uint32_t j = mx; j > 0; j >>= 1)
        {
            if (task != 2)
            {
                if (sol + j < n)
                    if (v[sol + j] <= x)
                        sol += j;
            }
            else
            {
                if (sol > j)
                    if (v[sol - j] >= x)
                        sol -= j;
            }
        }

        int result = sol;
        switch (task)
        {
        case 0:
            if (v[sol] != x)
                result = -2;
        }
        fout << result + 1 << endl;
    }

    fout.close();
    fin.close();

    return 0;
}