Cod sursa(job #2926312)

Utilizator Rares132Anea Rares Rares132 Data 17 octombrie 2022 17:46:19
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, a[100003];
// cea mai mare pozitie p a[p] = x
int cb0(int x)
{
    int st = 1, dr = n, mij, p = -1;
    while(st <= dr)
    {
        mij = (st + dr) / 2;
        if (a[mij] == x)
        {
            p = mij;
            st = mij + 1;
        }
        else if (a[mij] < x)
            st = mij + 1;
        else
            dr = mij - 1;
    }
    return p;
}
// cea mai mare pozitie p cu a[p] <= x
int cb1(int x)
{
    int st = 1, dr = n, mij, p = -1;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        if (a[mij] <= x)
        {
            p = mij;
            st = mij + 1;
        }
        else
            dr = mij - 1;
    }
    return p;
}
// cea mai mica pozitie p cu a[p] >= x
int cb2(int x)
{
    int st = 1, dr = n, mij, p = -1;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        if (a[mij] >= x)
        {
            p = mij;
            dr = mij - 1;
        }
        else
            st = mij + 1;
    }
    return p;
}
void Citire()
{
    int i, m, op, x;
    fin >> n;
    for (i = 1; i <= n; i++)
        fin >> a[i];
    fin >> m;
    for (i = 1; i <= m; i++)
    {
        fin >> op >> x;
        if(op == 0)
            fout << cb0(x) << "\n";
        if (op == 1)
            fout << cb1(x) << "\n";
        if (op == 2)
            fout << cb2(x) << "\n";
    }
}

int main()
{
    Citire();
    fout.close();
    return 0;
}