Cod sursa(job #2145901)

Utilizator UnseenMarksmanDavid Catalin UnseenMarksman Data 27 februarie 2018 18:00:11
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <cstdio>
using namespace std;

int n,q,v[100002];

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

    if(v[mid]>x) mid--;
    if(v[mid]==x)
        return mid;
    return -1;
}

int solve1(int x)
{
    int st=1, dr=n, mid, pos=1;
    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 solve2(int x)
{
    int st=1, dr=n, pos=n, mid;
    while(st<dr)
    {
        mid=st+(dr-st)/2;
        if(x<v[mid])
        {
            st=mid+1;
        }
        else
        {
            dr=mid;
        }
    }

    mid=st+(dr-st)/2;
    if(v[mid]<x)
    {
        ++mid;
    }
    return mid;
}

int main()
{
    int task,x;

    ios_base::sync_with_stdio(false);
    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);

    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>v[i];
    }
    cin>>q;
    while(q)
    {
        cin>>task>>x;
        if(task==0)
        {
            cout<<solve0(x)<<'\n';
        }
        else if(task==1)
        {
            cout<<solve1(x)<<'\n';
        }
        else
        {
            cout<<solve2(x)<<'\n';
        }
        q--;
    }
    return 0;
}