Cod sursa(job #3138236)

Utilizator alex210046Bratu Alexandru alex210046 Data 18 iunie 2023 11:30:49
Problema Cautare binara Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int v[100000], n;

int cautBin1(int x)
{
    int p = 1, u = n, poz = -1;
    while(p <= u)
    {
        int m = (p + u) / 2;
        if(x == v[m])
        {
            poz = m;
            p = m + 1;
        }
        else
        if(x > v[m])
            p = m + 1;
        else
            u = m - 1;
    }
    if(poz < 0)
        return poz;
    else
        return poz + 1;
}

int cautBin2(int x)
{
    int p = 1, u = n, poz = -1;
    while(p <= u)
    {
        int m = (p + u) / 2;
        if(x >= v[m])
        {
            poz = m;
            p = m + 1;
        }
        else
        if(x > v[m])
            p = m + 1;
        else
            u = m - 1;
    }

    return poz;
}

int cautBin3(int x)
{
    int p = 1, u = n, poz = -1;
    while(p <= u)
    {
        int m = (p + u) / 2;
        if(x <= v[m])
        {
            poz = m;
            u = m - 1;
        }
        else
        if(x > v[m])
            p = m + 1;
        else
            u = m - 1;
    }
    return poz;
}

int main() {
    f >> n;
    for(int i = 0; i < n; i++)
        f >> v[i];
    int m, x, y; f >> m;
    while (m --) {
        f >> x >> y;
        if(x == 0)
            g << cautBin1(y) << '\n';
        else if(x == 1)
            g << cautBin2(y) + 1 << '\n';
        else if(x == 2)
            g << cautBin3(y) + 1 << '\n';
    }

    return 0;
}