Cod sursa(job #2201412)
Utilizator | Data | 4 mai 2018 18:00:31 | |
---|---|---|---|
Problema | Cautare binara | Scor | 100 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.55 kb |
#include <stdio.h>
int n,m,x,v;
int a[100001];
int main()
{
int i,st,dr,mij,opt;
FILE *f,*g;
f=fopen("cautbin.in","r");
g=fopen("cautbin.out","w");
fscanf(f,"%d",&n);
for(i=1;i<=n;i++)
fscanf(f,"%d ",&a[i]);
fscanf(f,"%d",&m);
for(i=1;i<=m;i++)
{
fscanf(f,"%d%d",&v,&x);
st=1;dr=n;
if(v==0)
{
opt=-1;
while(st<=dr)
{
mij=st+(dr-st)/2;
if(x==a[mij])
{
opt=mij;
st=mij+1;
continue;
}
if(x<a[mij])
dr=mij-1;
else
st=mij+1;
}
}
if(v==2)
{
while(st<=dr)
{
mij=st+(dr-st)/2;
if(a[mij]>=x)
{
opt=mij;
dr=mij-1;
continue;
}
else
st=mij+1;
}
}
if(v==1)
{
while(st<=dr)
{
mij=st+(dr-st)/2;
if(a[mij]<=x)
{
opt=mij;
st=mij+1;
continue;
}
else
dr=mij-1;
}
}
fprintf(g,"%d\n",opt);
}
fclose(f);
fclose(g);
}