Cod sursa(job #2280610)

Utilizator cristianabalcanuCristiana Balcanu cristianabalcanu Data 10 noiembrie 2018 21:48:18
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");
int n, m, v[100003], w, c;


int cerinta0(int x )
{
    int st = 1, dr = n, mid;
    int pos = -1;
    while (st <= dr)
    {
        mid = st + (dr - st) / 2;
        if (v[mid] == x)
        {
            pos = mid;
            st = mid + 1;
        }
        else if ( v[mid] < x )
            st = mid + 1;
        else if ( v[mid] > x )
            dr = mid - 1;
        else
            st = st + 1;
    }
    return pos;
}

// upper_bound
int cerinta1(int x )
{
    int st = 1, dr = n, mid;
    while (st < dr)
    {
        mid = st + (dr - st) / 2;
        if (v[mid] <= x)
            st = mid + 1;
        else
            dr = mid;
    }
    mid = st + (dr - st) / 2;
    if(v[mid] > x)
        mid--;
    return mid;
}

int cerinta2( int x )
{
    int st = 1, dr = n, mid;
    while (st < dr)
    {
        mid = st + (dr - st) / 2;
        if (v[mid] < x)
            st = mid + 1;
        else
            dr = mid;
    }
    mid = st + (dr - st) / 2;
    if(v[mid] < x)
        mid++;
    return mid;
}

int main()
{
    int i;
    // citire
    fin >> n;
    for ( i = 1 ; i <= n ; i++ )
        fin >> v[i];

    fin >> m;
    for ( i = 1 ; i <= m ; i++ )
    {
        fin >> c >> w;
        if ( c == 0 )
            fout << cerinta0(w) << endl;
        else if ( c == 1 )
            fout << cerinta1(w) << endl;
        else
            fout << cerinta2(w) << endl;

    }
    return 0;
}