Cod sursa(job #2549898)

Utilizator Alin_StanciuStanciu Alin Alin_Stanciu Data 18 februarie 2020 08:58:54
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb

#include <iostream>

#include <fstream>

using namespace std;

ifstream fin("cautbin.in");

ofstream fout("cautbin.out");

int n, m, A[100002];

int Cb1(int x)

{

int st = 1, dr = n;

while (st <= dr)

{

int mij = (st + dr) / 2;

if (A[mij] <= x)

st = mij + 1;

else dr = mij - 1;

}

return dr;

}

int Cb2(int x)

{

int st = 1, dr = n;

while (st <= dr)

{

int mij = (st + dr) / 2;

if (A[mij] < x)

st = mij + 1;

else dr = mij - 1;

}

return st;

}

int main()

{

fin >> n;

for (int i = 1; i <= n; ++i)

fin >> A[i];

fin >> m;

for (int i = 1; i <= m; ++i)

{

int c, x;

fin >> c >> x;

if (c == 0)

{

if (A[Cb1(x)] == x)

fout << Cb1(x) << '\n';

else fout << -1 << '\n';

}

else if (c == 1)

fout << Cb1(x) << '\n';

else fout << Cb2(x) << '\n';

}

return 0;

}