Cod sursa(job #660291)

Utilizator dutzulBodnariuc Dan Alexandru dutzul Data 12 ianuarie 2012 00:32:43
Problema Cautare binara Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#define l 100000
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int i,x,v[l],m,s,n,t;
int bs1(int z)
{
    int step=s,p=0;
    for(p=0; step; step/=2)
        if (p+step<=n&&v[p+step]<=z) p+=step;

    if (v[p]==z)return p;
    else return -1;
}
int bs2(int z)
{
    int step=s,p=0;
    for(p=0; step; step/=2)
        if (p+step<=n&&v[p+step]<=z) p+=step;
    return p;
}
int bs3(int z)
{
    int step=s,p=0;
    for(p=0; step; step/=2)
        if (p+step<=n&&v[p+step]<z) p+=step;
    return p+1;
}
int main()
{
    f>>n;
    for(s=1; s*2<=n; s=s*2);
    for(i=1; i<=n; i++)f>>v[i];
    f>>m;

    for(i=1; i<=m; i++)
    {
        f>>t>>x;
        if (t==0) g<< bs1(x)<<'\n';
        if (t==1) g<< bs2(x)<<'\n';
        if (t==2) g<< bs3(x)<<'\n';
    }


    f.close();
    g.close();
    return 0;
}