Cod sursa(job #1877064)

Utilizator cautionPopescu Teodor caution Data 12 februarie 2017 21:30:18
Problema Cautare binara Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>

const int kMaxN = 100000;

int v[kMaxN + 1];

int main()
{
	freopen("cautbin.in", "rt", stdin);
	freopen("cautbin.out", "wt", stdout);
	int n, m;

	scanf("%d", &n);
	for (int i = 0; i < n; ++i) {
		scanf("%d", v + i);
	}

	scanf("%d", &m);
	for (int i = 0; i < m; ++i) {
		int op, x, step, k;

		scanf("%d%d", &op, &x);	

		step = 1;
		while (step <= n) step <<= 1;
		step >>= 1;
		k = 0;
		
		switch (op) {
		case 0:
			while (step) {
				if (k + step < n && v[k + step] <= x) k += step;
				step >>= 1;
			}
			if (v[k] == x) printf("%d\n", k + 1);
			else printf("-1\n");
			break;
		case 1:
			while (step) {
				if (k + step < n && v[k + step] <= x) k += step;
				step >>= 1;
			}
			printf("%d\n", k + 1);
			break;
		case 2:
			while (step) {
				if (k + step < n && v[k + step] < x) k += step;
				step >>= 1;
			}
			printf("%d\n", k + 2);
			break;
		}
	}

	return 0;
}