Cod sursa(job #3149058)

Utilizator PetraPetra Hedesiu Petra Data 5 septembrie 2023 23:41:36
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n, m, a[100002];

int op0(int x, int st, int dr)
{
    if (st > dr) return -1;
    int mijl = (st+dr) / 2;
    if (a[mijl]==x) return mijl;
    if (a[mijl] > x) return op0(x, st, mijl - 1);
    if (a[mijl] < x) return op0(x, mijl + 1, dr);
}

int main()
{
    fin >> n;
    for (int i = 1; i <= n; i++)
        fin >> a[i];
    fin >> m;
    for (int i = 0; i < m; i++)
    {
        int c, x;
        fin >> c >> x;
        int poz = op0(x, 1, n);

        if (c == 0)
        {
            if (poz == -1)
            {
                fout << -1;
                continue;
            }
            int poz_copy = poz;
            while (a[poz_copy] == x)
                poz_copy++;
            fout << poz_copy - 1 << "\n";
        }
        if (c == 1)
        {
            int poz_copy = poz;
            while (a[poz_copy] <= x)
                poz_copy++;
            fout << poz_copy - 1 << "\n";
        }
        if (c == 2)
        {
            int poz_copy = poz;
            while (a[poz_copy] >= x)
                poz_copy--;
            fout << poz_copy + 1 << "\n";
        }
    }
    return 0;
}