Cod sursa(job #3316619)

Utilizator luqnq_bBalasa Luana Catinca luqnq_b Data 19 octombrie 2025 14:31:05
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int v[100002];

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