Cod sursa(job #1051869)

Utilizator PsychoAlexAlexandru Buicescu PsychoAlex Data 10 decembrie 2013 17:24:52
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <fstream>

std::ifstream fin("cautbin.in");
std::ofstream fout("cautbin.out");

int vec[100001], n, m, poz1;

int binSearch(int in, int sf, int val)
{
    int m;
    while(in <= sf)
    {
        m = (in + sf) / 2;
        if(vec[m] < val)
        {
            in = m+1;
        }
        else
            if(vec[m] > val)
            {
                sf = m-1;
            }
            else
            {
                return m;
            }
    }
    m = (in + sf) / 2;
        return m;
}

void rezolvare(int x, int y)
{
    int raspuns = -1;
    if(x == 0)
    {
        int val = binSearch(0, n-1, y);
        if(vec[val] == y)
        {
            int i = val;
            while(i < n && vec[i] == y)
            {
                i++;
            }
            raspuns = i;
        }
    }
    else
        if(x == 1)
        {
            int val = binSearch(0, n-1, y);
            int i = val;
            while(i < n && vec[i] <= y)
            {
                i++;
            }
            raspuns = i;
        }
        else
            if(x == 2)
            {
                int val = binSearch(0, n-1, y);
                int i = val + 1;
                int j = i;
                while(i >= 0 && vec[i] >= y)
                {
                    j = i;
                    i--;
                }
                raspuns = j + 1;
            }
    if(raspuns > n)
    {
        raspuns = n;
    }
    fout<<raspuns<<'\n';
}

void citire()
{
    fin>>n;
    for(int i = 0; i < n; i++)
    {
        fin>>vec[i];
    }
    fin>>m;
    int x, y;
    for(int i = 0; i < m; i++)
    {
        fin>>x>>y;
        rezolvare(x, y);
    }
}

int main()
{
    citire();
    return 0;
}