Cod sursa(job #2336755)
Utilizator | Data | 5 februarie 2019 15:42:19 | |
---|---|---|---|
Problema | Cautare binara | Scor | 0 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 2.15 kb |
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int main()
{
int n , v[1001],i;
fin>>n;
for(i=1;i<=n;i++)
{
fin>>v[i];
}
int caz,x,cazu,st,dr;
int m;
fin>>caz;
while(caz!=0)
{
fin>>cazu>>x;
if(cazu==0)
{
st=1,dr=n;
while(st!=dr)
{
m=(st+dr)/2;
if(v[m]>x)
{
dr=m;
}
else if(v[m]<x)
{
st=m+1;
}else
{
if(v[m+1]>x)
{
break;
}else
{
st=m+1;
}
}
}
if(v[m]==x)
{
fout<<m<<"\n";
}else
{
fout<<-1<<"\n";
}
}
if(cazu==1)
{
st=1,dr=n;
while(st!=dr)
{
m=(st+dr)/2;
if(v[m]>x)
{
dr=m;
}
else if(v[m]<x)
{
st=m+1;
}else
{
if(v[m+1]>x)
{
break;
}else
{
st=m+1;
}
}
}
fout<<m<<"\n";
}
if(cazu==2)
{
st=1,dr=n;
while(dr-st>1)
{
m=(dr+st)/2;
if(v[m]>=x)
{
dr=m;
}
else
{
st=m+1;
}
}
fout<<dr<<"\n";
}
caz--;
}
return 0;
}