Cod sursa(job #562210)

Utilizator Rares95Rares Arnautu Rares95 Data 22 martie 2011 16:56:22
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
	
	# include <fstream>
	using namespace std;
	
	int t, x, n, tip, i;
	int a[ 100001 ];
	
	int cautbin1 ( int x ) {
		int i, cnt = 1 << 20;
		for ( i = 1; cnt; cnt >>= 1 ) {
			if ( i + cnt <= n ) {
				if ( a[ i + cnt ] <= x ) i += cnt;
			}
		}
		if ( !tip && a[ i ] != x ) return -1;
		return i;
	}
	
	int cautbin2 ( int x ) {
		int st = 1, dr = n, mij;
		while ( st <= dr ) {
			mij = ( st + dr ) >> 1;
			if ( a[ mij ] >= x ) dr = mij - 1;
			else st = mij + 1;
		}
		if ( a[ mij ] < x ) return mij + 1;
		return mij;
	}
	
	int main () {
		
		ifstream f ( "cautbin.in" );
		ofstream g ( "cautbin.out");
		
		f >> n;
		
		for ( i = 1; i <= n; ++i ) f >> a[ i ];
		
		for ( f >> t; t; --t ) {
			
			f >> tip >> x;
			
			if ( tip < 2 ) g << cautbin1 ( x ) << '\n';
			else g <<cautbin2 ( x ) << '\n';
			
		}
		
		g.close ();
		return 0;
	}