Cod sursa(job #1887963)

Utilizator kons7aConstantinescu Andrei kons7a Data 21 februarie 2017 20:56:03
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.56 kb
#include <iostream>
#include <fstream>

using namespace std;

int st, dr, n, sir[100005], i, m, mij, x, z, p, c;
bool gata;

int main()
{
    ifstream f("cautbin.in");
    ofstream g("cautbin.out");
    f >> n;
    for(i=1;i<=n;i++)
    {
        f >> sir[i];
    }
    f >> m;
    for(z=1;z<=m;z++)
    {
        st = 1;
        dr = n;
        gata = 0;
        f >> p >> x;
        if(p==0)
        {
            while((st<=dr)&&(!gata))
            {
                mij = (st + dr) / 2;
                if(x==sir[mij])
                {
                    c = mij;
                    gata = 1;
                    while(sir[c]==x)
                    {
                        c++;
                    }
                    c = c - 1;
                    g << c << endl;
                }
                else
                {
                    if(x > sir[mij])
                        st = mij + 1;
                    else
                        dr = mij - 1;
                }
            }
            if(gata==0)
                g << -1 << endl;
        }
        if(p==1)
        {
            while((st<=dr)&&(!gata))
            {
                mij = (st + dr) / 2;
                if(x==sir[mij])
                {
                    c = mij;
                    gata = 1;
                    while(sir[c]==x)
                    {
                        c++;
                    }
                    c = c - 1;
                    g << c << endl;
                }
                else
                {
                    if(x > sir[mij])
                        st = mij + 1;
                    else
                        dr = mij - 1;
                }
            }
            if(gata==0)
                g << dr << endl;
        }
        if(p==2)
        {
            while((st<=dr)&&(!gata))
            {
                mij = (st + dr) / 2;
                if(x==sir[mij])
                {
                    c = mij;
                    gata = 1;
                    while(sir[c]==x)
                    {
                        c--;
                    }
                    c = c + 1;
                    g << c << endl;
                }
                else
                {
                    if(x > sir[mij])
                        st = mij + 1;
                    else
                        dr = mij - 1;
                }
            }
            if(gata==0)
                g << st << endl;
        }
    }
    g.close();
    f.close();
    return 0;
}