Cod sursa(job #1358624)

Utilizator cristian.enciuCristian Enciu cristian.enciu Data 24 februarie 2015 18:30:23
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<stdio.h>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
	freopen("cautbin.in", "r", stdin);
	freopen("cautbin.out", "w", stdout);

	int n; scanf("%d", &n);
	vector<int> v;

	int x;
	for(int i = 0 ; i < n && scanf("%d", &x) ; ++i) v.push_back(x); 

	int m; scanf("%d", &m);

	for(; m ; --m) {
		int type, val;
		scanf("%d%d", &type, &val);

		if(type == 0) {
			vector<int>::iterator it = lower_bound(v.begin(), v.end(), val);
			if(it != v.end() && !(val < *it)) {
				for(; val = *it ; ++it);
				printf("%d\n", it - v.begin());
			} else printf("-1\n");
		} else if(type == 1) {
			vector<int>::iterator it = lower_bound(v.begin(), v.end(), val);
			if(it != v.end() && (val == *it)) printf("%d\n", it - v.begin());
			else printf("%d\n", it - v.begin() - 1);
		} else if(type == 2) {
			vector<int>::iterator it = upper_bound(v.begin(), v.end(), val);
			if(it != v.end() && (val == *it)) printf("%d\n", it - v.begin());
			else printf("%d\n", it - v.begin() + 1);
		}
	}

	return 0;
}