Cod sursa(job #3209617)

Utilizator tudorhorotanHorotan Tudor tudorhorotan Data 2 martie 2024 23:03:11
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 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;
        }
    }
    int auxpoz = poz;
    while(v[auxpoz] <= v[poz]) {
        ++auxpoz;
    }
    return auxpoz - 1;
}

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;
        }
    }
    int auxpoz = poz;
    while(v[auxpoz] >= v[poz]) {
        --auxpoz;
    }
    return auxpoz + 1;
}

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) {
        int auxpoz = poz;
        while (v[auxpoz] == x) {
            ++auxpoz;
        }
        return auxpoz - 1;
    } 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 (y == 2) {
            fout << caut2(n, x) << "\n";
        } else if (y == 0){
            fout << caut0(n, x) << "\n";
        }
    }

    return 0;
}