Cod sursa(job #2093508)

Utilizator BlaiddBlaidd Blaidd Blaidd Data 23 decembrie 2017 21:15:21
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <fstream>

using namespace std;

int n, t, a[100001];
int caut0(int x)
{
    int st = 1, dr = n, mij;

    while(st < dr)
    {
        mij = st + (dr - st) / 2;
        if(x >= a[mij])
            st = mij + 1;
        if(x < a[mij])
            dr = mij - 1;
    }
    if(a[st] == x)
        return st;
    if(a[st - 1] == x)
        return st - 1;
    return -1;
}
int caut1(int x)
{
    int st = 1, dr = n, mij, auxst = -1;

    while(st <= dr)
    {
        mij = st + (dr - st) / 2;
        if(x >= a[mij])
        {
            auxst = mij;
            st = mij + 1;
        }
        else
        {
            dr = mij - 1;
        }
    }

    return auxst;
}
int caut2(int x)
{
    int st = 1, dr = n, mij, auxdr = -1;
    while(st <= dr)
    {
        mij = st + (dr - st) / 2;
        if(x > a[mij])
        {
            st = mij + 1;
        }
        else
        {
            auxdr = mij;
            dr = mij - 1;
        }
    }

    return auxdr;
}
void citire()
{
    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");

    fin >> n;
    for(int i = 1; i <= n; i++)
    {
        fin >> a[i];
    }
    fin >> t;
    for(int i = 0; i < t; i++)
    {
        int c, x;
        fin >> c >> x;
        if(c == 0)
            fout << caut0(x) << endl;
        if(c == 1)
            fout << caut1(x) << endl;
        if(c == 2)
            fout << caut2(x) << endl;
    }
}
int main()
{
    citire();
    return 0;
}
/*
   if(a[st] == x)
    {
        if(a[auxst] < a[st])
            return auxst;
        else
            return st;
    }
    if(a[st - 1] == x)
    {
        if(a[auxst] < a[st - 1])
            return auxst;
        else
            return st - 1;
    }
*/

/*
 while(st < dr)
    {
        if(x >= a[mij])
            st = mij + 1;
        else
            dr = mij - 1;
    cout << st << " " << dr << endl;
    }
    if(a[st] == x)
        return st;
    if(a[st - 1] == x)
        return st - 1;
*/