Cod sursa(job #3138234)

Utilizator alex_0747Gheorghica Alexandru alex_0747 Data 18 iunie 2023 11:18:24
Problema Cautare binara Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

int a[100005], n, q;

int CB1(int x);
int CB2(int x);
int CB3(int x);

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

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

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

int main()
{
	int i, op, x;
	fin >> n;
	for (i = 1; i <= n; i++)
		fin >> a[i];
	fin >> q;
	while (q--)
	{ 
		fin >> op >> x;
		switch (op) {
		case 0:
			fout << CB1(x) << "\n";
			break;
		case 1:
			fout << CB2(x) << "\n";
			break;
		case 2:
			fout << CB3(x) << "\n";
			break;
		}
	}
	return 0;
}