Cod sursa(job #3219404)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 31 martie 2024 12:36:15
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <stdint.h>

const int32_t MAX_N = 100000;
const int32_t MAX_N_POW_2 = 1 << 16;

int32_t vec[MAX_N];
int main() {
    std::ifstream fin("cautbin.in");
    std::ofstream fout("cautbin.out");

    int32_t n;
    fin >> n;
    for(int32_t i = 0; i != n; ++i)
        fin >> vec[i];
    
    int32_t m;
    fin >> m;
    for(int32_t i = 0; i != m; ++i) {
        int32_t c, x;
        fin >> c >> x;

        int32_t pos;
        switch(c) {
        case 0:
            pos = 0;
            for(int32_t step = MAX_N_POW_2; step; step >>= 1)
                if(pos + step < n && vec[pos + step] <= x)
                    pos += step;
            if(vec[pos] != x)
                pos = -2;
            break;
        case 1:
            pos = 0;
            for(int32_t step = MAX_N_POW_2; step; step >>= 1)
                if(pos + step < n && vec[pos + step] <= x)
                    pos += step;
            break;
        case 2:
            pos = n;
            for(int32_t step = MAX_N_POW_2; step; step >>= 1)
                if(pos >= step && vec[pos - step] >= x)
                    pos -= step;
            break;
        }

        fout << (pos + 1) << '\n';
    }

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

    return 0;
}