Cod sursa(job #1206920)

Utilizator an_drey_curentandreycurent an_drey_curent Data 11 iulie 2014 15:07:57
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include<stdio.h>
int N, M, *A;
FILE *in, *out;
int binarySearch(int left, int right, int x)
{
	int middle = left + ((right - left) / 2);
	if (left > right) return middle;

	if (A[middle] == x)
		return middle;
	if (A[middle] < x)
		return binarySearch(middle + 1, right, x);
	if (A[middle] > x)
		return binarySearch(left, middle - 1, x);
}
void read()
{
	in = fopen("cautbin.in", "rt");
	out = fopen("cautbin.out", "wt");

	fscanf(in, "%d", &N);
	A = new int[N + 5];
	for (int i = 1; i <= N; i++)
	{
		fscanf(in, "%d", &A[i]);
	}
}
void process(){
	fscanf(in, "%d", &M);
	while (M--)
	{
		int type, x, foundIndex;
		fscanf(in, "%d %d", &type, &x);
		foundIndex = binarySearch(1, N, x);
		
		switch (type)
		{
			case 0:
				if (A[foundIndex] != x) 
					fprintf(out, "-1\n");
				else
				{
					while (A[foundIndex] == x && foundIndex <= N) foundIndex++;
					fprintf(out, "%d\n", foundIndex-1);
				}
				break;
			case 1:
				if (A[foundIndex] > x)
					fprintf(out, "%d\n", foundIndex-1);
				else
				{
					while (A[foundIndex] <= x && foundIndex <= N) foundIndex++;
					fprintf(out, "%d\n", foundIndex-1);
				}
				break;
			case 2:
				if (A[foundIndex] < x)
					fprintf(out, "%d\n", foundIndex + 1);
				else
				{
					while (A[foundIndex] >= x && foundIndex > 0) foundIndex--;
					fprintf(out, "%d\n", foundIndex+1);
				}
				break;
			default:
				break;
		}
	}
}
int main()
{
	read();
	process();
	delete[] A;
	return 0;
}