Cod sursa(job #3037553)

Utilizator ArcopieBirghilescu Alexandru Arcopie Data 25 martie 2023 19:31:02
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
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)
{
    while(st<=dr){
    int m=(st+dr)/2;
    if(v[m]<x)
            return cautare1(v,m+1,dr,x);
    else if(v[m]<=x && v[m+1]==x)return cautare1(v,m+1,dr,x);
    else if(v[m]<=x && v[m+1]>x )return m;
    else if(v[m]>x)return cautare1(v,st,m-1,x);
    }


}
int cautare2(int v[], int st, int dr, int x)
{
    while(st<=dr){
    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 if(v[m]<x)cautare2(v,m+1,dr,x);
    }



}
int main()
{
    int n,m,x,intrebare;
    fin>>n;
    int v[n+1];
    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;
        }
        if(intrebare==1)fout<<'\n'<<cautare1(v,1,n,x);
        if(intrebare==2)fout<<'\n'<<cautare2(v,1,n,x);

    }




    return 0;
}