Cod sursa(job #629282)

Utilizator stef2nStefan Istrate stef2n Data 3 noiembrie 2011 01:06:15
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.62 kb
#include <algorithm>
#include <fstream>
using namespace std;

int N, M;
int x[100001];

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

	fin >> N;
	for (int i = 0; i < N; ++i)
		fin >> x[i];

	fin >> M;
	for (int i = 0; i < M; ++i) {
		int op, elem, *p;
		fin >> op >> elem;
		if (op == 0) {
			p = upper_bound(x, x + N, elem);
			if (p == x || *(p - 1) != elem)
				fout << "-1\n";
			else
				fout << (p - x) << "\n";
		} else if (op == 1) {
			p = upper_bound(x, x + N, elem);
			fout << (p - x) << "\n";
		} else {
			p = lower_bound(x, x + N, elem);
			fout << (p - x + 1) << "\n";
		}
	}
	return 0;
}