Cod sursa(job #326024)

Utilizator crisojogcristian ojog crisojog Data 23 iunie 2009 14:18:53
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include<stdio.h>
long n,m,x,a,i,j,c[100010],poz[100010];
long part(long st, long dr)
{
	long i,j,pivot,aux,m;
	m=(st+dr)/2;
	pivot=c[m];
	i=st-1;j=dr+1;
	while(1)
	{
		do{++i;} while(c[i]<pivot);
		do{--j;} while(c[j]>pivot);
		if(i<j)
		{
			if(c[i]!=c[j])
			{
				aux=c[i];
				c[i]=c[j];
				c[j]=aux;
				aux=poz[i];
				poz[i]=poz[j];
				poz[j]=aux;
			}
			else
			{
				if(poz[i]>poz[j])
				{
					aux=c[i];
					c[i]=c[j];
					c[j]=aux;
					aux=poz[i];
					poz[i]=poz[j];
					poz[j]=aux;
				}
			}
		}
		else return j;
	}
}
void quicks(long st, long dr)
{
	long p;
	if(st<dr)
	{
		p=part(st,dr);
		quicks(st,p);
		quicks(p+1,dr);
	}
}
long cautbin0()
{
	long st, dr, m;
	st=1;dr=n;
	while(st<=dr)
	{
		m=(st+dr)/2;
		if(a<c[m]) dr=m-1;
		else if(a>c[m]) st=m+1;
		else return poz[m];
	}
	return -1;
}
long cautbin1()
{
	long st, dr, m, u;
	st=1;dr=n;
	while(st<=dr)
	{
		m=(st+dr)/2;
		if(a>=c[m]) 
		{
			u=poz[m];
			st=m+1;
		}
		else dr=m-1;
	}
	return u;
}
long cautbin2()
{
	long st, dr, m, u=n+1;
	st=1;dr=n;
	while(st<=dr)
	{
		m=(st+dr)/2;
		if(a<=c[m]) 
		{
			u=poz[m];
			dr=m-1;
		}
		else st=m+1;
	}
	return u;
}
int main()
{
	freopen("cautbin.in","r",stdin);
	freopen("cautbin.out","w",stdout);
	scanf("%ld",&n);
	for(i=1;i<=n;++i)
		scanf("%ld",&c[i]);
	for(i=1;i<=n;++i) poz[i]=i;
	quicks(1,n);
	scanf("%ld",&m);
	for(i=1;i<=m;++i)
	{
		scanf("%d%ld",&x,&a);
		if(x==0)
		{
			printf("%ld\n",cautbin0());			
		}
		if(x==1)
		{
			printf("%ld\n",cautbin1());			
		}
		if(x==2)
		{
			printf("%ld\n",cautbin2());			
		}
	}
}