Cod sursa(job #1451900)

Utilizator theprdvtheprdv theprdv Data 18 iunie 2015 22:11:48
Problema Cautare binara Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100000

int N, M, LOG, X[MAXN];
bool ex, found;

int search(int eq, int val){
	int step = LOG, k = 0;

	for (; step; step >>= 1){
		if (k + step >= N) continue;
		else if (eq && X[k + step] <= val) k += step;
		else if (!eq && X[k + step] < val) k += step;
	}
	if (ex && X[k] == val) found = 1;
	if (!eq && k + 1 < N) return ++k;
	return k;
}

int main(void)
{
	FILE *fin = fopen("cautbin.in", "r") , *fout = fopen("cautbin.out", "w");

	fscanf(fin, "%d", &N);
	for (int i = 0; i < N; ++i)
		fscanf(fin, "%d", &X[i]);
	for (LOG = 1; LOG < N; LOG <<= 1);

	fscanf(fin, "%d", &M);
	for (int i = 0, val, x, pos; i < M; ++i, found = ex = 0){
		fscanf(fin, "%d %d", &x, &val);
		if (!x) ex = 1;
		pos = search(x < 2 ? 1 : 0, val) + 1;
		fprintf(fout, "%d\n", !x ? found ? pos : -1 : pos);
	}
	
	fclose(fin), fclose(fout);
	return 0;
}