Cod sursa(job #3317001)

Utilizator luqnq_bBalasa Luana Catinca luqnq_b Data 21 octombrie 2025 17:27:57
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");

int v[100002];

int main()
{
    int n;
    fin >> n;
    for (int i=1; i<=n; i++)
        fin >> v[i];
    int m, c, x;
    fin >> m;
    int poz = 0, mijl;
    while ( m > 0 )
    {
        int st = 1;
        int dr = n;
        poz = -1;
        fin >> c >> x;
        while ( st <= dr )
        {
            mijl = st + ( dr - st ) / 2;
            if ( v[mijl] == x )
            {
                poz = mijl;
                break;
            }
            if ( v[mijl] > x )
                dr = mijl - 1;
            if ( v[mijl] < x )
                st = mijl + 1;
        }
        if ( c == 0 )
        {
            if ( poz == mijl )
            {
                while ( v[poz] == x && poz <= n )
                    poz++;
                poz--;
                fout << poz << "\n";
            } else 
                fout << -1 << "\n";
        } 
        if ( c == 1 )
        {
            if ( poz == mijl )
            {
                while ( v[poz] == x && poz <= n )
                    poz++;
                poz--;
                fout << poz << "\n";
            } else 
                fout << st - 1 << "\n";
        }
        if ( c == 2 )
        {
            if ( poz == mijl )
            {
                while ( v[poz] == x && poz >= 1 )
                    poz--;
                poz++;
                fout << poz << "\n";
            } else 
                fout << dr + 1 << "\n";
        }
        m--;
    }
    
    
    
    return 0;
}