Cod sursa(job #2941109)
Utilizator | Data | 17 noiembrie 2022 09:56:55 | |
---|---|---|---|
Problema | Cautare binara | Scor | 10 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.45 kb |
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
long long n,i,a[1001],m,st,dr,x,nri,caz,poz;
int main()
{
fin>>n;
for(i=1;i<=n;i++)
fin>>a[i];
fin>>nri;
while(nri)
{
fin>>caz>>x;
if(caz==2)
{
st=1;
dr=n;
poz=0;
while(st<=dr)
{
m=(st+dr)/2;
if(a[m]>=x)
{
poz=m;
dr=m-1;
}
else st=m+1;
}
fout<<poz<<'\n';
}
else if(caz==0)
{
st=1;
dr=n;
poz=0;
while(st<=dr)
{
m=(st+dr)/2;
if(a[m]==x)
{
poz=m;
st=m+1;
}
else dr=m-1;
}
if(poz==0)fout<<-1<<'\n';
else fout<<poz<<'\n';
}
else
{
st=1;
dr=n;
poz=0;
while(st<=dr)
{
m=(st+dr)/2;
if(a[m]<=x)
{
poz=m;
st=m+1;
}
else dr=m-1;
}
fout<<poz<<'\n';
}
nri--;
}
}