Cod sursa(job #2266504)

Utilizator gheorghe-eduGheorghe Eduard gheorghe-edu Data 22 octombrie 2018 18:47:02
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>

using namespace std;

int v[100001],n,m;

const int c=16;

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

void citire()
{
    in>>n;
    for(int i=1; i<=n; i++)
        in>>v[i];
    in>>m;
}

int caut0 (int x)
{
    int r=0,pas=1<<c;
    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<<c;
    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<<c;
    while(pas!=0)
    {
        if(r+pas<=n && v[r+pas]<x)
        {
            r+=pas;
        }
        pas/=2;
    }
    r++;
    return r;
}

int main()
{
    citire();
    int t,x;
    for(int i=0; i<m; i++)
    {
        in>>t>>x;
        if(t==0) out << caut0 (x);
        if(t==1) out << caut1 (x);
        if(t==2) out << caut2 (x);
        out << "\n";
    }

    return 0;
}