Cod sursa(job #1234897)

Utilizator vtt271Vasile Toncu vtt271 Data 28 septembrie 2014 12:05:35
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>

using namespace std;

ifstream inFile("cautbin.in");
ofstream outFile("cautbin.out");

int A[100005], n, m;

int binry_search0(int st, int dr, int x)
{
	while( st < dr ){
		int mid = st + ( dr - st )/2;
		if( A[mid] <= x )  st = mid + 1;
		if( A[mid] > x )   dr = mid - 1;
	}

	if( A[st] == x ) return st;
	if( A[st-1] == x ) return st-1;
	return -1;
}

int binry_search1(int st, int dr, int x)
{
	while( st < dr ){
		int mid = st + ( dr - st )/2;
		if( A[mid] <= x )  st = mid + 1;
		if( A[mid] > x )   dr = mid - 1;
	}

	if( A[st] <= x ) return st;
	if( A[st-1] <= x ) return st-1;
	return -1;
}

int binry_search2(int st, int dr, int x)
{
	while( st < dr ){
		int mid = st + ( dr - st )/2;
		if( A[mid] >= x )  dr = mid - 1;
		if( A[mid] < x )   st = mid + 1;
	}

	if( A[dr] == x ) return dr;
	if( A[dr+1] == x ) return dr+1;
	return -1;
}


int main()
{
	inFile >> n;

	for(int i = 1; i <= n; i++){
		inFile >> A[i];
	}

	inFile >> m;

	int op, x;
	while(m--){
		inFile >> op >> x;

		if( op == 0 ) outFile << binry_search0(1, n, x) << "\n";
		if( op == 1 ) outFile << binry_search1(1, n, x) << "\n";
		if( op == 2 ) outFile << binry_search2(1, n, x) << "\n";
	}

	
}