Pagini recente » Cod sursa (job #2407265) | Cod sursa (job #122933) | Cod sursa (job #214937) | Cod sursa (job #1297715) | Cod sursa (job #2010165)
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("cautbin.in");
ofstream out("cautbin.out");
const int NMAX = 100003;
int genlower(int n) ///Generare Numar pow2 <= n
{
int x;
for(x=1; x<=n; x=x*2)
{}
return x/2;
}
int binarysearch2(int x,int v[],int n)
{
int step = genlower(n);
int sol;
for( sol=1; step>=1; step=step/2)
{
if(sol+step<=n && v[sol+step]<=x)
{
sol+=step;
}
}
return sol;
}
int binarysearch1(int x,int v[],int n)
{
int step = genlower(n);
int sol;
for(sol=n; step>=1; step=step/2)
{
if(sol-step>0 && v[sol-step]>=x)
{
sol-=step;
}
}
return sol;
}
int main()
{
int n;
int v[NMAX];
int t;
in>>n;
for(int i=1; i<=n; i++)
{
in>>v[i];
}
in>>t;
for(int i=1; i<=t; i++)
{
int s,x;
in>>s>>x;
if(s==0)
{
int temp=binarysearch2(x,v,n);
if(v[temp]==x)
out<<temp<<'\n';
else
out<<-1<<'\n';
}
else if(s==1)
{
out<<binarysearch2(x,v,n)<<'\n';
}
else
{
out<<binarysearch1(x,v,n)<<'\n';
}
}
}