Cod sursa(job #3170392)

Utilizator gabriela15Popescu Gabriela Irina gabriela15 Data 17 noiembrie 2023 15:57:36
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>

using namespace std;
const int NMAX=100000;

int N, v[NMAX+1];

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

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

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

int caut2(int x)
{
    int st=1, dr=N, m, poz=-1;
    while(st<=dr)
    {
        m=(st+dr)/2;
        if(x<=v[m])
        {
            poz=m;
            dr=m-1;
        }
        else
            st=m+1;
    }
    return poz;
}

int main()
{
    int M, x, t;
    f >> N;
    for(int i=1; i<=N; i++)
        f >> v[i];
    f >> M;
    while(M--)
    {
        f >> t >> x;
        switch(t)
        {
            case 0: g << caut0(x) << '\n';
                    break;
            case 1: g << caut1(x) << '\n';
                    break;
            case 2: g << caut2(x) << '\n';
                    ///break;
        }
    }
    f.close();
    g.close();
    return 0;
}