Cod sursa(job #2778742)

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

int n, m;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int binary_search(int find, int left, int right, int vec[]) {
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (vec[mid] == find) {
            return mid;
        } else if (find > vec[mid]) {
            left = mid + 1;
        } else if (find < vec[mid]) {
            right = mid - 1;
        }
    }
    return -1;
}

int main() {
    fin >> n;
    int vec[n + 1];
    for (int i = 1; i <= n; ++i) {
        fin >> vec[i];
    }
    fin >> m;
    while (m--) {
        int condition, x;
        fin >> condition >> x;
        int poz = binary_search(x, 1, n, vec);
        if (condition == 0 || condition == 1) {
            if (poz != -1) {
                while (poz <= n && vec[poz] == x) {
                    ++poz;
                }
                    fout << poz - 1<< '\n';
            } else {
                fout << - 1 << '\n';
            }
        } else if (condition == 2) {
           while (poz >= 1 && vec[poz] == x) {
              --poz;
           }
           fout << poz + 1<< '\n';
        }
      }
    return 0;
}