Cod sursa(job #2857873)

Utilizator LORDENVraja Luca LORDEN Data 26 februarie 2022 15:26:19
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>

using namespace std;

ifstream cin ("cautbin.in") ;
ofstream cout ("cautbin.out") ;

int n, q, v[100005] ;

int bsearch (int x, int st, int dr)
{

    int mij ;

    while (st <= dr)
    {

        mij = (st + dr) / 2 ;

        if (x < v[mij])
            dr = mij - 1 ;

        else if (x > v[mij])
            st = mij + 1 ;

        else if (x == v[mij])
            return mij ;

    }

    return -1 ;

}

int main()
{

    int type, x ;

    cin >> n ;

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

    cin >> q ;

    for (int i = 1 ; i <= q ; i ++)
    {

        cin >> type >> x ;

        int pos = bsearch (x, 1, n) ;

        if (type == 0)
        {

            if (pos == -1)
                cout << -1 ;

            else
            {

                while (v[pos] == v[pos + 1])
                    pos ++ ;

                cout << pos << '\n' ;

            }

        }

        else if (type == 1)
        {

            while (v[pos] == v[pos + 1])
                pos ++ ;

            cout << pos << '\n' ;

        }

        else
        {

            while (v[pos] == v[pos - 1])
                pos -- ;

            cout << pos << '\n' ;

        }

    }

    return 0 ;

}