Cod sursa(job #221658)

Utilizator Sorin_IonutBYSorynyos Sorin_Ionut Data 17 noiembrie 2008 16:43:58
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <cstdio>
#define MAX_N 100010

int A[MAX_N], N, M;

int caut_bin0( int alfa ) {
	int total, step;
	for ( step=1; step<=N; step <<= 1 );
	for ( total=0; step; step >>= 1 )
		if ( step+total <= N && A[step+total] <= alfa )
			total += step;
	return ( A[ total ] == alfa ) ? total : -1;
}

int caut_bin1( int alfa ) { 
	int total, step;
	for ( step=1; step<=N; step <<= 1 );
	for ( total=0; step; step >>= 1 )
		if ( step+total <= N && A[step+total] <= alfa )
			total += step;
	return total;
}

int caut_bin2( int alfa ) { 
	int total, step;
	for ( step=1; step<=N; step <<= 1 );
	for ( total=N; step; step >>= 1 )
		if ( total-step  > 0 && A[total-step] >= alfa )
			total -= step;
	return total;
}

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

	scanf("%d", &N);
	for ( int i=1; i<=N; ++i ) scanf("%d", A+i);
	scanf("%d", &M);
	while ( M-- ) {
		int tip, x;
		scanf("%d %d\n", &tip, &x);
		switch ( tip ) {
			case 0:
				printf("%d\n", caut_bin0(x));
				break;
			case 1:
				printf("%d\n", caut_bin1(x));
				break;
			case 2:
				printf("%d\n", caut_bin2(x));
		}
	}
	return 0;
}