Cod sursa(job #2615788)

Utilizator iuliaaa2110Barbu Iulia Andreea iuliaaa2110 Data 15 mai 2020 15:45:25
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>

std::ifstream f ("cautbin.in");
std::ofstream g ("cautbin.out");

int v[100001], n, q;

void f0(int x, int st, int dr, int poz)
{
    if(st<=dr)
    {
        int m=st+(dr-st)/2;

        if(v[m]==x)
        {
            if(poz<m)
                poz=m;

            f0(x,m+1,dr,poz);
        }

        else
        {
            if(v[m]<x)
                f0(x,m+1,dr,poz);

            else
                f0(x,st,m-1,poz);
        }
    }
    else
        g<<poz+1<<'\n';

}

void f1(int x, int st, int dr, int poz)
{
    if(st<=dr)
    {
        int m=st+(dr-st)/2;

        if(v[m]==x)
        {
            poz=m;
            f1(x,m+1,dr,poz);
        }
        else
        {
            if (v[m]<x)
            {
                if(poz<m)
                    poz=m;

                f1(x,m+1,dr,poz);
            }
            else
                f1(x,st,m-1,poz);
        }
    }
    else
        g<<poz+1<<'\n';

}

void f2(int x, int st, int dr, int poz)
{
    if(st<=dr)
    {
        int m=st+(dr-st)/2;

        if(v[m]==x)
        {
            if(poz>m)
                poz=m;

            f2(x,st,m-1,poz);
        }
        else
        {
            if(v[m]<x)
                f2(x,m+1,dr,poz);
            else
            {
                if(poz>m)
                    poz=m;

                f2(x,st,m-1,poz);
            }
        }
    }
    else
        g<<poz+1<<'\n';

}

int main()
{
    f>>n;
    for(int i=0; i<n; i++)
        f>>v[i];
    f>>q;

    for(int i=0; i<q; i++)
    {
        int x, y;

        f>>x>>y;

        if(x==0)
            f0(y, 0, n-1, -2);

        if (x==1)
            f1(y, 0, n-1, -2);

        if (x==2)
            f2(y, 0, n-1, n);
    }

    return 0;
}