Cod sursa(job #2073091)

Utilizator VladimirPopa123Vladimir Popa VladimirPopa123 Data 22 noiembrie 2017 18:19:20
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include<fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");

int caut_0(int);
int caut_1(int);
int caut_2(int);

int v[100001],n;

int main()
{
    int m,c,x;
    fin>>n;
    for(int i=1; i<=n; i++) fin>>v[i];
    fin>>m;
    for(int i=1; i<=m; i++)
    {
        fin>>c>>x;
        switch(c)
        {
        case 0:
            fout<<caut_0(x)<<"\n";
            break;
        case 1:
            fout<<caut_1(x)<<"\n";
            break;
        case 2:
            fout<<caut_2(x)<<"\n";
            break;
        }
    }
    return 0;
}

int caut_0(int x)
{
    int pas,r=0;
    pas=1<<16;
    while(pas)
    {
        if(r+pas<=n&&v[r+pas]<=x) r+=pas;
        pas/=2;///pas>>=1;
    }///r este ultimul care are proprietatea
    if(v[r]!=x) r=-1;
    return r;
}

int caut_1(int x)
{
    int pas,r=0;
    pas=1<<16;
    while(pas)
    {
        if(r+pas<=n&&v[r+pas]<=x) r+=pas;
        pas/=2;
    }
    return r;
}

int caut_2(int x)
{
    int pas,r=0;
    pas=1<<16;
    while(pas)
    {
        if(r+pas<=n&&v[r+pas]<x) r+=pas;
        pas/=2;
    }
    r++;
    return r;
}