Cod sursa(job #2231879)

Utilizator anne_marieMessner Anne anne_marie Data 16 august 2018 13:32:34
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>

using namespace std;

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

int n, v[100005];

int f(int x)
{
    int stanga = 1, dreapta = n, mijloc, rasp = -1;
    //fout << "Aici";
    while( stanga <= dreapta )
    {
        //fout << "Cautam in intervalul " << stanga  << " " << dreapta << "; rasp = " << rasp << '\n';
        mijloc = ( stanga + dreapta ) / 2;
        if (v[mijloc] >= x)
            {
                rasp = mijloc;
                dreapta = mijloc - 1;
            }
        else
            {
                stanga = mijloc + 1;
            }

    }
    return rasp;
}

int ff(int x)
{
    int stanga = 1, dreapta = n, mijloc, rasp =-1;
    while ( stanga <= dreapta )
    {
         mijloc = ( stanga + dreapta ) / 2;
         if( v[mijloc] <= x)
         {
             rasp = mijloc;
             stanga = mijloc + 1;
         }
         else
         {
             dreapta = mijloc - 1;
         }
    }
    return rasp;
}


int main()
{
    fin >> n;
    for ( int i = 1 ; i <= n ; i++)
    {
        fin >> v[i];
    }
    int m;
    fin >> m;
    for ( int i = 1 ; i <= m ; i++)
    {
        int q, x, poz;
        fin >> q >> x;
        if( q == 2)
            fout << f(x) << '\n';
        else
            if ( q == 0 )
            {
                poz = ff(x);
                if( v[poz] == x)
                    fout << poz << '\n';
                else
                    fout << -1 << '\n';
            }
            else
                fout << ff(x) << '\n';
    }
        return 0;
}