Pagini recente » Cod sursa (job #2629765) | Cod sursa (job #438608) | Cod sursa (job #1425422) | Cod sursa (job #289272) | Cod sursa (job #926260)
Cod sursa(job #926260)
#include <iostream>
#include <fstream>
using namespace std;
int a[100001],n,x,y,i,k,ok,j,m,p;
int main()
{
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
fin>>n;
for(i=1;i<=n;i++)fin>>a[i];
fin>>m;
for(k=1;k<=m;k++)
{
fin>>p>>x;
i=1;j=n;ok=1;
if(p==0)
{
do{
y=(i+j)/2;
if(a[y]==x)
{
while(a[y+1]==x){y++;}
ok=0;
}
else if(a[y]>x)i=y+1;
else j=y-1;
}while((ok==1)&&(i<=j));
if(i<=j)fout<<y<<"\n";
else fout<<-1<<"\n";
}
if(p==1)
{
do{
y=(i+j)/2;
if(a[y]<=x){while(a[y+1]<=x){y++;}ok=0;}
else if(a[y]>x)i=y+1;
else j=y-1;
}while((ok==1)&&(i<=j));
fout<<y<<"\n";
}
if(p==2)
{
do{
y=(i+j)/2;
if(a[y]>=x){while(a[y-1]>=x){y--;}ok=0;}
else if(a[y]>x)i=y+1;
else j=y-1;
}while((ok==1)&&(i<=j));
fout<<y<<"\n";
}
}
fin.close();
fout.close();
return 0;
}