Cod sursa(job #3165297)

Utilizator Nita.stefanNita Stefan Ianis Nita.stefan Data 5 noiembrie 2023 20:24:49
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

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

int a[100001], n, i = 1, M, c, x;

int Caut1(int x)
{
    int st = 1, dr = n;
    while(st<=dr)
    {
        int m = (st+dr) / 2;
        if(a[m] <= x)
            st = m + 1;
        else
            dr = m - 1;
    }
    int m = (st + dr) / 2;
    if(a[m] > x)
        m--;
    else if(a[m] == x)
        return m;
    return -1;
}

int Caut2(int x)
{
    int st = 1, dr = n;
    while(st<dr)
    {
        int m = (st+dr) / 2;
        if(a[m] <= x)
            st = m + 1;
        else
            dr = m;
    }
    int m = (st + dr) / 2;
    if(a[m] > x)
        m--;
    return m;
}

int Caut3(int x)
{
    int st = 1, dr = n;
    while(st<dr)
    {
        int m = (st+dr) / 2;
        if(a[m] < x)
            st = m + 1;
        else
            dr = m;
    }
    int m = (st + dr) / 2;
    if(a[m] < x)
        m++;
    return m;
}

int main()
{
    fin >> n;
    for(i = 1;i <= n;i++)
        fin >> a[i];
    fin >> M;
    while(M!= 0)
    {
        fin >> c >> x;
        if(c == 0)
            fout << Caut1(x) << '\n';
        else if(c == 1)
            fout << Caut2(x) << '\n';
        else if(c == 2)
            fout << Caut3(x) << '\n';
        M--;
    }
    return 0;
}