Cod sursa(job #2073089)

Utilizator valeriucaraselCarasel Valeriu valeriucarasel Data 22 noiembrie 2017 18:18:54
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>

using namespace std;

const int L=16;

int v[100005],n,m;

int caut0 (int x)
{
    int pas,r;
    pas=1<<L;
    r=0;
    while (pas!=0)
    {
        if ((r+pas<=n)&&(v[r+pas]<=x))
        {
            r+=pas;
        }
        pas>>=1;
    }
    if (v[r]!=x)
    {
        r=-1;
    }
    return r;
}

int caut2(int x)
{
    int pas,r;
    pas=1<<L;
    r=0;
    while (pas!=0)
    {
        if ((r+pas<=n)&&(v[r+pas]<x))
        {
            r+=pas;
        }
        pas>>=1;
    }
    r++;
    return r;
}

int caut1(int x)
{
    int pas,r;
    pas=1<<L;
    r=0;
    while (pas!=0)
    {
        if ((r+pas<=n)&&(v[r+pas]<=x))
        {
            r+=pas;
        }
        pas>>=1;
    }
    return r;
}

int main()
{
    ifstream in("cautbin.in");
    ofstream out("cautbin.out");
    in>>n;
    int i;
    for (i=1;i<=n;i++)
    {
        in>>v[i];
    }
    in>>m;
    int cer,x;
    for (i=1;i<=m;i++)
    {
        in>>cer>>x;
        if (cer==0) out<<caut0(x)<<"\n";
        else
        if (cer==1) out<<caut1(x)<<"\n";
        else
            out<<caut2(x)<<"\n";
    }
    in.close();
    out.close();
    return 0;
}