Cod sursa(job #2229930)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 8 august 2018 14:56:51
Problema Cautare binara Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>
using namespace std;
int n, v[100005], m, c, i, x, poz, st;
void binarysearch(int x, int & poz, int & st)
{
    st = 1;
    int dr = n;
    while(st <= dr)
    {
        int mij = (st + dr) / 2;
        if(v[mij] == x)poz = mij, st = dr + 1;
        else if(v[mij] > x)dr = mij - 1;
        else st = mij + 1;
    }
}
int main()
{
    ifstream f("cautbin.in");
    ofstream g("cautbin.out");
    f >> n;
    for(i = 1;i <= n;i++)
        f >> v[i];
    f >> m;
    for(i = 1;i <= m;i++)
    {
        f >> c >> x;
        poz = -1;
        binarysearch(x, poz, st);
        if(c == 0)
        {
            if(poz == -1)g << "-1" << "\n";
            else
            {
                while(v[poz + 1] == v[poz])poz++;
                g << poz << "\n";
            }
        }
        if(c == 1)
        {
            if(poz != -1)
            {
                while(v[poz + 1] == v[poz])poz++;
                g << poz << "\n";
            }
            else
            {
                while(v[st] > x)st--;
                while(v[st] <= x)st++;
                g << st - 1 << "\n";
            }
        }
        if(c == 2)
        {
            if(poz != -1)
            {
                while(v[poz - 1] == v[poz])poz--;
                g << poz << "\n";
            }
            else
            {
                while(v[st] < x)st++;
                while(v[st] > x)st--;
                g << st + 1 << "\n";
            }
        }
    }
    return 0;
}