Cod sursa(job #629640)

Utilizator George25Raduta George Cristian George25 Data 3 noiembrie 2011 16:33:52
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include<stdio.h>

int poz,i,n,m,x,y,a[100001];

inline void cb1(int yy){
	int st,mij,dr;
	st=1;
	poz=-1;
	dr=n;
	mij=(st+dr)/2;
	while (st<dr)
	{
		if (a[mij]<yy)
		{
			st=mij+1;
			mij=(st+dr)/2;
		}
		if (a[mij]>yy)
		{
			dr=mij-1;
			mij=(st+dr)/2;
		}
		if (a[mij]==yy)	
		{
			poz=mij;
			st+=2;
			mij=(st+dr)/2;
		}
	}
}

inline void cb2(int yy){
	int st,mij,dr;
	st=1;
	dr=n;
	mij=(st+dr)/2;
	while (st<dr)
	{
		if (a[mij]>yy)
		{
			dr=mij;
			mij=(st+dr)/2;
		}
		if (a[mij]<yy)
		{
			poz=mij;
			st=mij+1;
			mij=(st+dr)/2;
		}
		if (a[mij]==yy)
		{
			poz=mij;
			st+=2;
			mij=(st+dr)/2;
		}
	}
}

inline void cb3(int yy){
	int st,dr,mij;
	st=1;
	dr=n;
	mij=(st+dr)/2;
	poz=0;
	while (st<dr && st>0)
	{
		if (a[mij]<yy)
		{
			st=mij+1;
			mij=(st+dr)/2;
		}
		if (a[mij]==yy)
		{
			poz=mij;
			dr-=2;
			mij=(st+dr)/2;
		}
		if (a[mij]>yy)
		{
			poz=mij;
			dr=mij;
			mij=(st+dr)/2;
		}
	}
}

int main(){
	freopen("cautbin.in","r",stdin);
	freopen("cautbin.out","w",stdout);
	scanf("%d",&n);
	for (i=1; i<=n; ++i) scanf("%d",&a[i]);
	scanf("%d",&m);
	for (i=1; i<=m; ++i)
	{
		scanf("%d %d",&x,&y);
		if (x==0)
		{
			cb1(y);
			printf("%d\n",poz);
		}
		if (x==1)
		{
			cb2(y);
			printf("%d\n",poz);
		}
		if (x==2)
		{
			cb3(y);
			printf("%d\n",poz);
		}
	}
	return(0);
}