Cod sursa(job #3204679)

Utilizator Nicholas123Tudose Nicholas Nicholas123 Data 17 februarie 2024 11:36:52
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
using namespace std;

int v[200005], n, x, poz, i, p, m;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");

int cautbin1(int x) {
    int ras, mij, st, dr;
    ras = -1;
    st = 1;
    dr = n;
    while (st < dr) {
        mij = (st + dr) / 2;
        if (v[mij] <= x) {
            ras = mij;
            st = mij + 1;
        } else
            dr = mij - 1;
    }
    return ras;
}

int cautbin2(int x) {
    int ras, mij, st, dr;
    st = 1;
    dr = n;
    ras = -1;
    while (st <= dr) {
        mij = (st + dr) / 2;
        if (v[mij] >= x) {
            ras = mij;
            dr = mij - 1;
        } else
            st = mij + 1;
    }
    return ras;
}

int cautbin0(int x) {
    int ras, mij, st, dr;
    ras = -1;
    st = 1;
    dr = n;
    while (st < dr) {
        mij = (st + dr) / 2;
        if (v[mij] == x) {
            ras = mij;
            st = mij + 1;
        } else
            dr = mij - 1;
    }
    return ras;
}

int main() {
    fin >> n;
    for (i = 1; i <= n; i++)
        fin >> v[i];
    fin >> m;
    for (i = 1; i <= m; i++) {
        fin >> p >> x;
        if (p == 0)
            poz = cautbin0(x);
        else if (p == 1)
            poz = cautbin1(x);
        else
            poz = cautbin2(x);
        fout << poz << '\n';
    }
    return 0;
}