Cod sursa(job #398700)

Utilizator mottyMatei-Dan Epure motty Data 19 februarie 2010 10:41:24
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include<stdio.h>

const int N=100001;

int n,m,v[N];

int caut( int x )
{
	int i,step;
	for( step=1 ; step<n ; step<<=1 );
	for( i=0 ; step ; step>>=1 )
		if( i+step<=n && v[i+step]<=x )
			i+=step;
	return i;
}

void read()
{
	int x,y,z;
	scanf("%d",&n);
	for( int i=1 ; i<=n ; ++i )
		scanf("%d",&v[i]);
	scanf("%d",&m);
	while(m--)
	{
		scanf("%d%d",&x,&y);
		z=caut(y);
		if(x==0)
		{
			if( v[z]==y )
				printf("%d\n",z);
			else
				printf("-1\n");
		}
		else if( x==1 )
			printf("%d\n",z);
		else
		{
			if( v[z]<y )
				++z;
			else
				while(v[z-1]==y )
					--z;
			printf("%d\n",z);
		}
	}
}

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