Cod sursa(job #3170520)

Utilizator andreisharkVirlan Andrei Cristian andreishark Data 17 noiembrie 2023 18:52:17
Problema Cautare binara Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.53 kb
#include <iostream>
#include <fstream>
#include <array>

#define Vec std::array<int, 150000>

int get_first_power(int pos) {
    int result = 1;

    while (result < pos)
        result <<= 1;

    if (result == pos) return result;
    return (result >> 1);
}

int get_second_power(int pos) {
    int result = 1;

    while (result < pos)
        result <<= 1;

    return result;
}

int binary_search_vec_1(const Vec& vec, int n, int x) {
    int pos = get_first_power(n - 1);
    int pos_final = 0;

    while (pos) {
        if (vec[pos + pos_final] <= x)
            pos_final += pos;

        pos >>= 1;
    }

    if (vec[pos_final] == x) return pos_final;
    return -1;
}

int binary_search_vec_2(const Vec& vec, int n, int x) {
    int pos = get_first_power(n - 1);
    int pos_final = 0;

    while (pos) {
        if (vec[pos + pos_final] <= x)
            pos_final += pos;

        pos >>= 1;
    }

    if (vec[pos_final] <= x) return pos_final;
    return -1;
}

int binary_search_vec_3(const Vec& vec, int n, int x) {
    int pos = get_second_power(n - 1);
    int pos_final = pos;

    pos >>= 1;
    while (pos) {
        if (vec[pos_final - pos] >= x)
            pos_final -= pos;

        pos >>= 1;
    }

    if (vec[pos_final] >= x) return pos_final;
    return -1;
}

int intrebare_1(const Vec& vec, int n, int x) {
    int pos = binary_search_vec_1(vec, n, x);
    return pos;
}
int intrebare_2(const Vec& vec, int n, int x) {
    int pos = binary_search_vec_2(vec, n, x);
    return pos;
}
int intrebare_3(const Vec& vec, int n, int x) {
    int pos = binary_search_vec_3(vec, n, x);
    return pos;
}

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

    Vec vec = {-1};

    int n, m;
    fin >> n;
    for (int i = 0; i < n; i++) {
        fin >> vec[i];
    }

    fin>>m;
    int command;
    int x;

    for (int i = 0; i < m; i++) {
        fin >> command >> x;
        int result;

        switch (command) {
        case 0:
            result = intrebare_1(vec, n ,x);
            if (result == -1) {
                fout << -1 << "\n";
                break;
            }
            fout << result + 1 << "\n";
            break;
        case 1:
            result = intrebare_2(vec, n, x) + 1;
            fout << result << "\n";
            break;
        case 2:
            result = intrebare_3(vec, n, x) + 1;
            fout << result << "\n";
            break;
        }
    }
}