Cod sursa(job #1496545)

Utilizator DobosDobos Paul Dobos Data 5 octombrie 2015 10:17:22
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("cautbin.in");
ofstream fout("cautbin.out");
int v[100006];
int caut(int li,int ls,int x)
{
    int mij = (li + ls) / 2;
    if(li >= ls)
        return mij;
    else{
    if(v[mij] == x)
        return mij;
    if(v[mij] < x){
            li = mij + 1;
            caut(li,ls,x);
            }
    else{
        ls = mij - 1;
        caut(li,ls,x);
    }
    }
}
int main()
{
    int n,m,x,p,poz;
    fin >> n;
    for(int i = 1; i <= n; i++)
        fin >> v[i];
    fin >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> p >> x;
        poz = caut(1,n,x);
        if( p == 0){
            if(v[poz] != x)
                fout << -1 << "\n";
            else{
                while(v[poz + 1] == x)
                    poz++;
                fout << poz <<"\n";
            }
        }
        if(p == 1){
                while(v[poz + 1] == x)
                    poz++;
                  fout << poz <<"\n";
        }
        if(p == 2){
            if(v[poz] == x)
                  while(v[poz - 1] == x)
                    poz--;
            else
                poz++;
        fout << poz << "\n";
        }
    }
    return 0;
}