Cod sursa(job #3037720)

Utilizator ArcopieBirghilescu Alexandru Arcopie Data 26 martie 2023 12:15:00
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int v[100001];
int cautare0(int v[], int st, int dr, int x)
{
    if(st>dr)return -1;
    else
    {
        int m=(st+dr)/2;
        if(v[m]==x && v[m+1]==x)
            return cautare0(v,m+1,dr,x);
        else if(v[m]==x && v[m+1]!=x)return m;
        else if(x<v[m])return cautare0(v,st,m-1,x);
        else
            return cautare0(v,m+1,dr,x);

    }

}
int cautare1(int v[], int st, int dr, int x)
{
    if(st==dr)return dr;
    else{

    int m=(st+dr)/2;
    if(v[m]==v[dr])return dr;
    else if(v[m]<=x && v[m+1]>x)return m;
    else if(v[m]<x)
            return cautare1(v,m+1,dr,x);

    else if(v[m]>x)return cautare1(v,st,m-1,x);
    }


}
int cautare2(int v[], int st, int dr, int x)
{

    if(st==dr)return dr;
    else{
    int m=(st+dr)/2;
    if(v[m]>=x && v[m-1]<x)return m;
    else if(v[m]>=x)cautare2(v,st,m-1,x);
    else
        cautare2(v,m+1,dr,x);
    }




}
int main()
{
    int n,m,x,intrebare;
    fin>>n;
    for(int i=1;i<=n;i++)fin>>v[i];
    fin>>m;
    int a;
    for(int i=1;i<=m;i++)
    {
        fin>>intrebare>>x;
        if(intrebare==0)
        {
            a=cautare0(v,1,n,x);
            fout<<a<<'\n';
        }
        if(intrebare==1)fout<<cautare1(v,1,n,x)<<'\n';
        if(intrebare==2)fout<<cautare2(v,1,n,x)<<'\n';

    }




    return 0;
}