Cod sursa(job #2620623)

Utilizator anamaria2602Avram Ana Maria anamaria2602 Data 29 mai 2020 12:27:40
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#define Maxx 100001

using namespace std;

ifstream f("cautbin.in");
ofstream g("cautbin.out");
int N,L,A[Maxx];
int M,x,y,poz,OK,st,dr,mij;
int CB(int A[],int &N,int y)
{
    poz = -1;
    OK = 0;
    st = 1;
    dr = N;
    while ( st<=dr )
    {
        mij = (st+dr)/2;
        if ( y == A[mij] )
        {
            poz = mij;
            OK = 1;
            return mij;
        }
        else if ( y<A[mij] )
            dr = mij-1;
        else if ( y>A[mij] )
            st = mij+1;
    }
    return st;
}
int pas1(int y)
{
    int poz = CB(A,N,y);
    while( A[poz+1]==A[poz] )
        poz++;
    if(OK==1)
        g << poz << endl;
    else
        g << "-1" << endl;
}
int pas2(int y)
{
    int poz = CB(A,N,y);
    if ( A[poz]!=y )
        poz--;
    g << poz << endl;
}
int pas3(int y)
{
    int poz = CB(A,N,y);
    while ( A[poz]==A[poz-1] )
        poz--;
    g << poz << endl;
}

int main()
{
    f >> N;
    for(int i=1; i<=N; i++)
        f >> A[i];
    f >> M;
    for(int i=1; i<=M; i++)
    {
        f >> x >> y;
        if ( x==0 )
            pas1(y);
        else if ( x==1 )
            pas2(y);
        else pas3(y);

    }
    return 0;
}