Cod sursa(job #429724)

Utilizator drywaterLazar Vlad drywater Data 30 martie 2010 13:35:58
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.66 kb
#include <stdio.h>
FILE *f=fopen("cautbin.in","r"),*g=fopen("cautbin.out","w");
int i,n,v[100001],m,k,d,t,x,q,ok;
int main(void)
{
	fscanf(f,"%d",&n);
	for (i=1;i<=n;i++)
		fscanf(f,"%d",&v[i]);
	fscanf(f,"%d",&m);
	k=1;
	while ((1<<k)<=n)
		k++;
	k--;
	for (i=1;i<=m;i++)
	{
		fscanf(f,"%d%d",&t,&x);
		q=k;
		d=0;
		ok=0;
		while (ok==0 && q>=0)
		{
			if ((d+(1<<q))<=n && v[d+(1<<q)]<=x)
				d+=(1<<q);
			q--;
		}
		if (t==0)
			if (v[d]==x) fprintf(g,"%d\n",d);
			else fprintf(g,"-1\n");
		else
		{
			if (t==1)
				fprintf(g,"%d\n",d);
			else {while (v[d]>=x) d--; d++; fprintf(g,"%d\n",d);}
		}
	}
	fclose(g);
	return 0;
}