Cod sursa(job #2266472)

Utilizator MicuMicuda Andrei Micu Data 22 octombrie 2018 18:20:06
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int L=16, N=100001;
int v[N], n;

int Caut0(int x)
{
    int r=0, pas=1<<L; //2^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;
    }
    return ++r;
}

int main()
{
    int m, i;
    f >> n;
    for(i=1;i<=n;i++) f >> v[i];
    f >> m;
    for(i=0;i<m;i++)
    {
        int tip, x;
        f >> tip >> x;
        if(tip==0) g << Caut0(x) << '\n';
        if(tip==1) g << Caut1(x) << '\n';
        if(tip==2) g << Caut2(x) << '\n';
    }
    f.close();
    g.close();
    return 0;
}