Cod sursa(job #1496684)

Utilizator DobosDobos Paul Dobos Data 5 octombrie 2015 13:12:01
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 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 ;
    while(li <= ls){
        mij = (li + ls) / 2;
    if(v[mij] == x)
          return mij;
    else{
    if(v[mij] < x)
            li = mij + 1;
    else
            ls = mij - 1;
    }
    }
    return mij;
}
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);
         //fout << poz << "\n";
        if( p == 0){
            if(v[poz] != x)
                fout << -1 << "\n";
            else{
                while(v[poz + 1] == x)
                    poz++;
                fout << poz <<"\n";
            }
        }
        if(p == 1){
                if(v[poz] == x)
                while(v[poz + 1] == x)
                    poz++;
                  else{
                    poz = caut(1,n,x - 1);
                     while(v[poz] > x)
                        poz--;
                     while(v[poz + 1] == v[poz])
                      poz++;
                  }
                    fout << poz <<"\n";

        }
        if(p == 2){
            if(v[poz] == x)
                  while(v[poz - 1] == x)
                    poz--;
            else{
                 poz = caut(1,n,x + 1);
                 while(v[poz] < x)
                    poz++;
                while(v[poz - 1] == v[poz])
                    poz--;
             }

        fout << poz << "\n";
        }
    }
    return 0;
}