Cod sursa(job #2426503)

Utilizator AlinaoAlina Curlat Alinao Data 28 mai 2019 14:19:27
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 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 caut_bin(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 = caut_bin(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 = caut_bin(1, n, x);
            if(v[pos] != x)
                pos--;
            fout << pos << '\n';
        }
        else{
            int pos = caut_bin(1, n, x);
            if(v[pos] == x)
                while(v[pos] == v[pos - 1])
                    pos--;
            fout << pos << '\n';
        }
    }
    fin.close();
    fout.close();
  return 0;
 }