Cod sursa(job #326469)

Utilizator ProcopliucProcopliuc Adrian Procopliuc Data 25 iunie 2009 11:35:01
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
# include <stdio.h>
int a[100005],i,j,n,m,q,ok,x,y;
void caut0 (int x)
{
int i=1,j=n,k;

ok=0;
while (ok==0 && i<=j)
{
k=(i+j)/2;
if (a[k]<x)
i=k+1;
else
if (a[k]>x)
j=k-1;
else
if (a[k+1]!=x)
ok=1;
else
j=k-1;
}
if (a[k]==x)
printf ("%i\n",k);
else
printf ("-1\n");
}
void caut1 (int x)
{
int i=1,j=n,k;
ok=0;
if (a[n]<=x)
k=n;
else
while (ok==0)
{
k=(i+j)/2;
if (a[k]<=x && a[k+1]>x)
ok=1;
else
if (x>a[k])
i=k+1;
else
j=k-1;
}
printf ("%i\n",k);
}
void caut2 (int x)
{
int i=1,j=n,k;
ok=0;
while (ok==0)
{
k=(i+j)/2;
if (a[k]>=x && a[k-1]<x)
ok=1;
else
if (a[k]<x)
i=k+1;
else
j=k-1;
}
printf ("%i\n",k);
}





int main ()
{
freopen ("cautbin.in","r",stdin);
freopen ("cautbin.out","w",stdout);
scanf ("%i",&n);
for (i=1;i<=n;i++)
scanf ("%i",&a[i]);
scanf ("%i",&m);
for (q=1;q<=m;q++)
{
scanf ("%i%i",&y,&x);
if (y==0)
caut0 (x);
if (y==1)
caut1 (x);
if (y==2)
caut2 (x);


}
return 0;
}