Cod sursa(job #2590546)

Utilizator AndreeaGherghescuAndreea Gherghescu AndreeaGherghescu Data 28 martie 2020 13:09:30
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream in ("cautbin.in");
ofstream out ("cautbin.out");

const int L=16;
const int N=100001;

int v[N],n;

int caut0 (int x)
{
    int r=0,pas=1<<L;
    while (pas!=0)
    {
        if (r+pas<=n && v[r+pas]<=x)
            r+=pas;
        pas/=2;
    }
    if (v[r]<x) return -1;
    return r;
}
int caut1 (int x)
{
    int r=0,pas=1<<L;
    while (pas!=0)
    {
        if (r+pas<=n && v[r+pas]<=x)
            r+=pas;
        pas/=2;
    }
    return r;
}
int caut2 (int x)
{
    int r=0,pas=1<<L;
    while (pas!=0)
    {
        if (r+pas<=n && v[r+pas]<x)
            r+=pas;
        pas/=2;
    }
    //if (v[r]<x) return -1;
    r++;
    return r;
}
int main()
{
    int cod,x,m;
    in>>n;
    for (int i=1;i<=n;i++)
        in>>v[i];
    in>>m;
    for (int i=1;i<=m;i++)
    {
        in>>cod>>x;
        if (cod==0)
        {
            out<<caut0(x)<<"\n";
        }
        else if (cod==1)
        {
            out<<caut1(x)<<"\n";
        }
        else
        {
            out<<caut2(x)<<'\n';
        }
    }
    return 0;
}