Cod sursa(job #1767189)

Utilizator jason2013Andronache Riccardo jason2013 Data 28 septembrie 2016 19:49:28
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include<bits/stdc++.h>
#define NMax 100100
using namespace std;

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

//array
int v[NMax];

//variables
int n,m,x,y;


int first(int y)
{
    int st = 1, dr = n, mij, gasit = 0;
    while (st <= dr && !gasit)
    {
        mij = (st+dr)/2;
        if (v[mij] == y)
            gasit = 1;
        else
            {
                if (v[mij] > y)
                    dr = mij - 1;
                else
                    st = mij;
            }
    }
    if (!gasit)
        return -1;
    //cautam cel mai mare y
    while (v[mij] == y && mij <= n)
        mij++;
    return mij-1;
}

int sec(int y)
{
    int st = 1, dr = n, mij;
    while (st < dr)
    {
        mij = (st+dr)/2;
        if (v[mij] <= y)
            st = mij + 1;
        else
            dr = mij;
    }
    mij = (st+dr)/2;
    if (v[mij] > y)
        mij--;
    return mij;
}

int third(int y)
{
    int st = 1, dr = n, mij
    while (st < dr)
    {
        mij = (st+dr)/2;
        if (v[mij] < y)
            st = mij + 1;
        else
            dr = mij;
    }
    mij = (st+dr)/2;
    if (v[mij] < y)
        mij++;
    return mij;
}

int main()
{
    in>>n;
    for(int i = 1; i<=n; i++)
        in>>v[i];
    in>>m;
    for(int i = 1; i<=m; i++)
    {
        in>>x>>y;
        if(x == 0)
           out<< first(y) << "\n";
        if(x == 1)
           out<< sec(y) <<"\n";
        if(x == 2)
           out<< third(y) <<"\n";
    }
}