Cod sursa(job #2853725)
Utilizator | Data | 20 februarie 2022 16:00:38 | |
---|---|---|---|
Problema | Cautare binara | Scor | 100 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.86 kb |
#include <bits/stdc++.h>
using namespace std;
ifstream fin("cautbin.in");
ofstream gout("cautbin.out");
int main()
{
int n,i,j,c,x,st,dr,m,mij;
fin>>n;
int v[n+1];
for(i=1;i<=n;++i)
{
fin>>v[i];
}
fin>>m;
for(i=1;i<=m;++i)
{
fin>>c>>x;
if(c==0)
{
st=1;
dr=n;
while(st<=dr)
{
mij=(st+dr)/2;
if(x>=v[mij])
{
st=mij+1;
}
else
{
dr=mij-1;
}
}
if(v[dr]==x)
{
gout<<dr<<'\n';
}
else
{
gout<<-1<<'\n';
}
}
else if(c==1)
{
st=1;
dr=n;
while(st<=dr)
{
mij=(st+dr)/2;
if(x>=v[mij])
{
st=mij+1;
}
else
{
dr=mij-1;
}
}
if(v[dr]<=x)
{
gout<<dr<<'\n';
}
else
{
gout<<dr-1<<'\n';
}
}
else
{
st=1;
dr=n;
while(st<=dr)
{
mij=(st+dr)/2;
if(x<=v[mij])
{
dr=mij-1;
}
else
{
st=mij+1;
}
}
if(v[st]>=x)
{
gout<<st<<'\n';
}
else
{
gout<<st+1<<'\n';
}
}
}
}