Cod sursa(job #2778532)

Utilizator paul911234vaida paul paul911234 Data 1 octombrie 2021 17:34:08
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int n, m, vec[100001];
int binary_search(int x, int left, int right) {
    int mid = (left + right) / 2;
    if (left > right) {
        return - 1;
    }
   if (vec[mid] == x) {
        return mid;
    } else if (x > vec[mid]) {
        binary_search(x, mid + 1, right);
    } else if (x < vec[mid]) {
        binary_search(x, left, mid - 1);
    }
}
void read(int n) {
    if (n == 0)
        return;
    read(n - 1);
    fin >> vec[n];
}
int main() {
    fin >> n;
    read(n);
    fin >> m;
    while (m--) {
        int condition, x;
        fin >> condition >> x;
        int poz = binary_search(x, 1, n);
        if (condition == 0 || condition == 1) {
            if (poz != -1) {
                while (poz <= n && vec[poz] == x) {
                    ++poz;
                }
                    fout << poz - 1<< '\n';
            } else {
                fout << - 1 << ' ';
            }
        } else if (condition == 2) {
           while (poz >= 1 && vec[poz] == x) {
              --poz;
           }
           fout << poz + 1 << '\n';
        }
      }
    return 0;
}