Cod sursa(job #1007535)

Utilizator otilia_sOtilia Stretcu otilia_s Data 9 octombrie 2013 00:54:20
Problema Cautare binara Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <fstream>

using namespace std;
const int NMAX = 100002;
int val, v[NMAX];

int binary_search(int lo, int hi, bool (*p) (int)) 
{
	while (lo < hi) {
		int mid = lo + (hi - lo) / 2;
		if ((*p)(v[mid]) == true)
			hi = mid;
		else
			lo = mid + 1;
	}
	
	if ((*p)(v[lo]) == false)
		return -1;
	return lo;
}

bool higher_val(int x) 
{
	return x > val;
}

bool higher_equal_val(int x) 
{
	return x >= val;
}

int main()
{
	ifstream fin("cautbin.in");
	ofstream fout("cautbin.out");
	
	int n, m;
	fin >> n;
	for (int i = 0; i < n; ++i)
		fin >> v[i];
	
	fin >> m;	
	while (m--) {
		int op;
		fin >> op >> val;
		int y;
		switch (op) {
			case 0:
				y = binary_search(0, n - 1, higher_val);
				if (y <= 0 || v[y - 1] != val)
					fout << -1 << endl;
				else
					fout << (y - 1) + 1 << endl;
				break;				
			case 1:
				y = binary_search(0, n - 1, higher_val);
				fout << (y - 1) + 1 << endl;
				break;
			case 2:
				y = binary_search(0, n - 1, higher_equal_val);
				fout << y + 1 << endl;
		}
	}
	
	return 0;
}