Cod sursa(job #1415593)

Utilizator CollermanAndrei Amariei Collerman Data 5 aprilie 2015 14:39:12
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include<fstream>

using namespace std;

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

const int MMAX = 100001;
int v[MMAX], n;

int caut1(int x)
{
    int ls, ld, mij;

    ls=1;
    ld=n;

    while(ls<=ld)
    {
        mij = ls + (ld - ls)/2;
        if( v[mij] == x )
        {
            while( v[mij] == v[mij + 1])
            {
                mij++;
            }
            return mij;
        }
        else
        {
            if( x > v[mij] ) ls = mij + 1;
            else ld = mij - 1;
        }
    }
    return -1;
}

int caut2(int x)
{
    int ls, ld, mij;

    ls=1;
    ld=n;

    while(ls<=ld)
    {
        mij = ls + (ld - ls)/2;
        if( v[mij] == x )
        {
            while( v[mij] == v[mij - 1])
            {
                mij--;
            }
            return mij;
        }
        else
        {
            if( x > v[mij] ) ls = mij + 1;
            else ld = mij - 1;
        }
    }
    return -1;
}

int main()
{
    int m, x, intreb, b, j;

    fin>>n;
    for(j=1; j<=n; j++)
    {
        fin>>v[j];
    }
    fin>>m;
    for(j=1; j<=m; j++)
    {
        fin>>intreb>>b;
        if(intreb == 0)
        {
            fout<<caut1(b)<<"\n";
        }
        else if(intreb == 1)
        {
            fout<<caut1(b)<<"\n";
        }
        else
        {
            fout<<caut2(b)<<"\n";
        }
    }
    return 0;
}