Cod sursa(job #2354594)

Utilizator Tudor_Trasculescu123Tudor Trasculescu Tudor_Trasculescu123 Data 25 februarie 2019 13:26:39
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>

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

unsigned int n , m , v[100005] , a , b , x ;

int caut(int l , int r , int x)
{
    int mij = 1 ;
    while(l <= r)
    {
        mij = (l + r) / 2 ;
        if(v[mij] > x)
            r = mij - 1 ;
        else if(v[mij] < x)
            l = mij + 1 ;
        else return mij ;
    }
    return mij ;
}

int main()
{
    fin >> n ;
    for(int i=1; i<=n; i++)
        fin >> v[i] ;
    fin >> m ;
    for(int i=1; i<=m; i++)
    {
        fin >> a >> b ;
        x = caut(1 , n , b) ;
        while(v[x+1] <= b && x<n)
            x ++ ;
        if(a == 0)
        {
            if(v[x] == b)
                fout << x << "\n";
            else
                fout << "-1" << "\n" ;
        }
        else if(a == 1)
            fout << x << "\n";
        else
        {
            while(v[x-1] >= b && x > 1)
              x -- ;
            if(v[x] >= b)
                fout << x << "\n" ;
            else fout << x + 1 << "\n" ;

        }
    }

    return 0;
}