Cod sursa(job #3288548)

Utilizator mcrg05Craciunescu Mihnea Gabriel mcrg05 Data 22 martie 2025 18:34:14
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include<bits/stdc++.h>

using namespace std;

const int MAXN = 1e5;
const int MAXM = 1e5;

int cb(int nr, int v[], int n){
    int acc = 0, pow_2 = 1 << 16;
    while(pow_2){
        int index = pow_2 + acc;
        if (index <= n && v[acc+pow_2] < nr) acc = index;
        pow_2 >>= 1;
    }
    return acc;
}

int main(){

    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");
    int n, m;
    fin >> n;
    int v[n];

    for (int i = 1; i <= n; ++i)
        fin >> v[i];

    fin >> m;
    
    int op, x, index;
    while(m--)
    {
        fin >> op >> x;
        if (op == 0){
            index = cb(x + 1, v, n);
            if (v[index] == x) fout << index << '\n';
            else fout << -1 << '\n';
        }
        if (op == 1){
                index = cb(x + 1, v, n);
                fout << index << "\n";
        }
        if (op == 2){
                index = cb(x, v, n);
                fout << index + 1 << "\n";
        }
    }
    return 0;
}