Cod sursa(job #2412835)

Utilizator Costy_Suruniuc Constantin Costy_ Data 22 aprilie 2019 16:31:25
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
using namespace std;

int N, A[100000];

int binary_search(int val)
{
	int i, step;
	for (step = 1; step < N; step <<= 1);
	for (i = 0; step; step >>= 1)
		if (i + step < N && A[i + step] <= val)
			i += step;
	return i;
}

int main()
{
	ifstream in;
	ofstream out;
	out.open("cautbin.out");
	in.open("cautbin.in");
	in >> N;
	for (int i = 0; i < N; i++)
	{
		in >> A[i];
	}
	int M;
	in >> M;
	while (M)
	{
		int op, val, temp;
		in >> op >> val;
		switch (op)
		{
		case 0:
			temp = binary_search(val);
			if (A[temp] != val)
			{
				out << -1 << '\n';
			}
			else
			{
				while (A[temp + 1] == val)
				{
					temp++;
				}
				out << temp + 1 << '\n';
			}
			break;
		case 1:
			do
			{
				temp = binary_search(val);
				if (A[temp] != val)
				{
					val--;
					temp = binary_search(val);
				}
				else
				{
					break;
				}
			} while (1);
			while (A[temp + 1] == val)
			{
				temp++;
			}
			out << temp + 1 << '\n';
			break;
		case 2:
			do
			{
				temp = binary_search(val);
				if (A[temp] != val)
				{
					val++;
					temp = binary_search(val);
				}
				else
				{
					break;
				}
			} while (1);
			while (A[temp - 1] == val)
			{
				temp--;
			}
			out << temp + 1 << '\n';
			break;
		}
		M--;
	}
	in.close();
	out.close();
}