Cod sursa(job #3208639)

Utilizator tudorhorotanHorotan Tudor tudorhorotan Data 29 februarie 2024 09:55:11
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");

int v[100001];

int caut1 (int n, int x) {
    int start = 1, stop = n, poz = n + 1;
    int mij = (start + stop) / 2;
    while (start <= stop) {
        mij = (start + stop) / 2;
        if (v[mij] >= x) {
            poz = mij;
            stop = mij - 1;
        } else {
            start = mij + 1;
        }
    }
    return poz;
}

int caut2 (int n, int x){
    int start = 1, stop = n, poz = 0;
    int mij = (start + stop) / 2;
    while (start <= stop) {
        mij = (start + stop) / 2;
        if (v[mij] >= x) {
            poz = mij;
            stop = mij - 1;
        } else {
            start = mij + 1;
        }
    }
    return poz;
}

int caut0 (int n, int x) {
    int start = 1, stop = n, poz = 0;
    while (start <= stop && poz == 0) {
        int mij = (start + stop) / 2;
        if(v[mij] == x) {
            poz = mij;
        } else {
            if (v[mij] > x) {
                start = mij + 1;
            } else {
                stop = mij - 1;
            }
        }
    }
    if (poz != 0) {
        return poz;
    } else {
        return -1;
    }
}

int main(){
    int n;
    fin >> n;
    for (int i = 1; i <= n; ++i) {
        fin >> v[i];
    }
    int m;
    fin >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> y >> x;
        if (y == 1) {
            fout << caut1(n, x) << "\n";
        } else if (x == 2) {
            fout << caut2(n, x) << "\n";
        } else {
            fout << caut0(n, x) << "\n";
        }
    }
    return 0;
}