Cod sursa(job #2386895)

Utilizator calin05Bordeanu Calin calin05 Data 23 martie 2019 20:49:11
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("cautbin.in");
ofstream g("cautbin.out");

int gasesteCelMaiStanga(vector<int> &vect, int x)
{
    int st = 0;
    int dr = vect.size()-1;
    int mid;
    while(st<=dr){
        mid = (st+dr)/2;
        if(x <= vect[mid])
            dr = mid-1;
        else st = mid+1;
    }
    return st;
}

int gasesteCelMaiDreapta(vector<int> &vect, int x)
{
    int st = 0;
    int dr = vect.size()-1;
    int mid;
    while(st<=dr){
        mid = (st+dr)/2;
        if(x >= vect[mid])
            st = mid+1;
        else dr = mid-1;
    }
    return dr;
}


int main()
{
    int n; f >> n;
    vector<int> vect(n);
    for(int i = 0; i<n; i++)
        f >> vect[i];

    int q; f >> q;
    for(int i = 0; i<q; i++){
        int query, x; f >> query >> x;
        int low = gasesteCelMaiStanga(vect, x);
        int high = gasesteCelMaiDreapta(vect, x);

        if(query == 0){
            if(vect[high]!=x) g << -1 << endl;
            else g << high+1 << endl;
        }
        else if(query == 1){
            g << high+1 << endl;
        }
        else g << low+1 << endl;
    }
}