Cod sursa(job #1448528)

Utilizator ioanac3caraian ioana ioanac3 Data 7 iunie 2015 13:28:27
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");

void citeste(int a[], int &n)
{
    f>>n;
    for(int i = 1; i <= n; i++)
        f>>a[i];
}

int ceaMaiMarePoz0(int a[], int n, int nr)
{
    int st = 1, dr = n,mij, pozMax = -1;
    while(st <= dr)
    {
        mij = (st+dr)/2;
        if(a[mij] == nr && pozMax < mij)
            pozMax = mij;
        if(a[mij] <= nr)
            st = mij+1;
        else
            dr = mij-1;
    }
    return pozMax;
}

int ceaMaiMarePoz1(int a[], int n, int nr)
{
    int st = 1, dr = n, mij, pozMax = -1;
    while(st <= dr)
    {
        mij = (st+dr)/2;
        if(a[mij] <= nr && pozMax < mij)
            pozMax =  mij;
        if(a[mij] <= nr)
            st = mij+1;
        else
            dr = mij-1;
    }
    return pozMax;
}

int ceaMaiMicaPoz(int a[], int n, int nr)
{
    int st = 1, dr = n, mij, pozMin = 100001;
    while(st <= dr)
    {
        mij = (st+dr)/2;
        if(a[mij] >= nr && pozMin > mij)
            pozMin = mij;
        if(a[mij] >= nr)
            dr = mij-1;
        else
            st = mij+1;
    }
    return pozMin;
}
int main()
{
    int a[100001],n,m;
    citeste(a,n);
    f>>m;
    for(int i = 1; i <= m; i++)
    {
        int op,nr;
        f>>op>>nr;
        if(op == 0)
            g<<ceaMaiMarePoz0(a,n,nr)<<endl;
        if(op == 1)
            g<<ceaMaiMarePoz1(a,n,nr)<<endl;
        if(op == 2)
            g<<ceaMaiMicaPoz(a,n,nr)<<endl;

    }
    return 0;
}