Cod sursa(job #3362069)

Utilizator iulia_toderica16Iulia Toderica iulia_toderica16 Data 1 august 2026 17:10:07
Problema Cautare binara Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>

using namespace std;

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

    int n, m, x, q;
    int v[100001];
    fin>>n;
    for(int i=0; i<n; i++)
        fin>>v[i];
    fin>>m;

    while(m--)
    {
        fin>>q>>x;
        int poz=-1;
        if(q==0)
        {
            int st=0, dr=n-1;
            //cea mai mare poz pe care o are x sau -1
            while(st<=dr)
            {
                int mij=st+(dr-st)/2;
                if(x==v[mij])
                {
                    poz=mij+1;
                    st=mij+1;
                }
                else if(x<v[mij])
                    st=mij+1;
                else
                    dr=mij-1;
            }

        }
        else if(q==1)
        {
            int st=0, dr=n-1, mij=-1;
            //cea mai mare poz pe care se afla un el mai <= x
            while(st<=dr)
            {
                int mij=st+(dr-st)/2;
                if(v[mij]<=x)
                {
                    poz=mij+1;
                    st=mij+1;
                }
                else
                    dr=mij-1;
            }

        }
        else if(q==2)
        {
            int st=0, dr=n-1, mij=-1;
            //cea mai mica poz pe care se afla un el >=x;
            while(st<=dr)
            {
                int mij=st+(dr-st)/2;
                if(v[mij]>=x)
                {
                    poz=mij+1;
                    dr=mij-1;
                }
                else
                    st=mij+1;
            }

        }
        fout<<poz<<'\n';
    }

    return 0;
}