Cod sursa(job #2619321)

Utilizator andreea.vasilescuAndreea Vasilescu andreea.vasilescu Data 27 mai 2020 14:28:28
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <iostream>
#define nmax 100005
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int n, v[nmax], q, c, x;
int cautbin(int st, int dr, int x){
    int mij;
    while(st <= dr){
        mij = (st + dr) / 2;
        if(x == v[mij])
            return mij;
        else if(x < v[mij])
            dr = mij - 1;
        else st = mij + 1;
    }
 return st;
 }
int main(){
    fin >> n;
    for(int i = 1; i <= n; ++i)
        fin >> v[i];
    fin >> q;
    for(int i = 1; i <= q; ++i){
        fin >> c >> x;
        if(c == 0){
            int pos = cautbin(1, n, x);
            while(v[pos] == v[pos + 1])
                pos++;
            if(v[pos] != x)
                pos = -1;
            fout << pos << '\n';
        }
        else if(c == 1){
            int pos = cautbin(1, n, x);
            if(v[pos] != x)
                pos--;
            fout << pos << '\n';
        }
        else{
            int pos = cautbin(1, n, x);
            if(v[pos] == x)
                while(v[pos] == v[pos - 1])
                    pos--;
            fout << pos << '\n';
        }
    }
    fin.close();
    fout.close();
  return 0;
 }