Cod sursa(job #1451925)

Utilizator theprdvtheprdv theprdv Data 18 iunie 2015 23:12:27
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 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 val){
	int step = LOG, k = 0;

	for (; step; step >>= 1)
		if (k + step >= N) continue;
		else if (X[k + step] <= val) k += step;
	if (ex && X[k] == val) found = 1;
	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;
		if (x == 2) --val;
		pos = search(val) + (x == 2 ? 2 : 1);
		if (x == 2 && X[0] >= ++val) --pos;
		fprintf(fout, "%d\n", !x ? found ? pos : -1 : pos);
	}

	fclose(fin), fclose(fout);
	return 0;
}