Cod sursa(job #3215853)

Utilizator lorenazLorena Zavelca lorenaz Data 15 martie 2024 13:39:24
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");

int a[100000];
int bin(int v[],int val, int n)
{
    int ans = 0, st = 1, dr = n, med = 0;
    while (st <= dr)
    {
        med = (st + dr)/2;
        if (v[med] <= val)
        {
           st = med + 1;
           ans = med;
        }
        else
           dr = med - 1;
    }
    return ans;
}

int main()
{
    int n;
    fin >> n;
    for (int i = 1; i <= n; i++)
    {
        fin >> a[i];
    }
    int m, t0, t1, t2;
    fin >> m;
    for (int i = 1; i <= m; i++)
    {
        int task, x;
        fin >> task >> x;
        int poz = bin(a, x, n);
        if (a[poz] == x)
            t0 = poz;
        else
            t0 = -1;
        if (t0 != -1)
        {
            /*if (poz != n)
                t1 = poz - 1;
            else
                t1 = poz;
            if (poz != 1)
                t2 = poz + 1;
            else
                t2 = poz;*/
            t1 = poz;
            if (poz == n)
                t2 = poz;
            else
                t2 = poz - 1;
        }
        else
        {
            t1 = poz;
            t2 = poz - 1;
        }
    }
    fout << t0 << '\n' << t1 << '\n' << t2;
    return 0;
}