Cod sursa(job #2145881)

Utilizator UnseenMarksmanDavid Catalin UnseenMarksman Data 27 februarie 2018 17:46:28
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 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 if(v[mid]>x)
        {
            dr=mid-1;
        }
        else
        {
            pos=mid;
            st=mid+1;
        }
    }
    return pos;
}

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

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

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;
}