Cod sursa(job #1732655)

Utilizator dinurosca1503Dinu Rosca dinurosca1503 Data 22 iulie 2016 10:31:45
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int v[100005];
//int cautbin(int ls, int ld, int x)
//{
//    int mij = ( ls + ld ) / 2;
//    if(x < mij)
//        return cautbin(ls, mij - 1, x);
//    else if(x > mij)
//        return cautbin( mij + 1,  ld, x);
//    else return mij;
//
//
//    return -1;
//}
int cautbin_iterativ(int ls, int ld, int x)
{
    int mij = (ls + ld) / 2;
    while(x < mij)
        mij = (ls + mij - 1) / 2;
    while(x > mij)
        mij = (mij + 1 + ld) / 2;
    if(v[mij] == x)
        return mij;
    else return -1;


}
int main()
{

    int n, m;
    int i, tip_intrebari, x;
    f >> n ;
    for(i = 1;i <= n;i++)
        f >> v[i];
    f >> m;
    for(i = 0;i < m;i++)
    {
        f >> tip_intrebari >> x;
        if(tip_intrebari == 0)
        {
            int gasit = cautbin_iterativ( 1,  n,  x);
            while(v[gasit + 1] == x)
                gasit++;
            g << gasit << endl;
        }
        if(tip_intrebari == 1)
        {
            int gasit = cautbin_iterativ(1, n, x);

            while(v[gasit + 1] == x)
                gasit++;
            g << gasit << endl;


        }
        if(tip_intrebari == 2)
        {
            int gasit = cautbin_iterativ(1, n, x);

            while(v[gasit - 1] == x)
                gasit--;
            g << gasit;
        }
    }




    return 0;
}