Cod sursa(job #432038)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 1 aprilie 2010 19:15:26
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>

using namespace std;

long sir[100100];
long N,M,maxstp;

void citire()
{
    scanf("%ld",&N);
    for(long i=1;i<=N;i++)
        scanf("%ld",&sir[i]);
    for(maxstp=1  ; maxstp<N ; maxstp<<=1);
}

int cauta(int val)
{
    int i,step=maxstp;
    for(i=0 ; step ; step >>= 1)
        if(step+i<=N && sir[i+step]<=val)
            i+=step;
    return i;
}

void solve()
{
    scanf("%ld",&M);
    int op,x;
    while(M--)
    {
        scanf("%d %d",&op,&x);
        if(op==2)
            printf("%d\n",cauta(x-1)+1);
        else if(op==1)
            printf("%d\n",cauta(x));
        else
        {
            int temp=cauta(x);
            if(sir[temp]==x)
                printf("%d\n",temp);
            else printf("-1\n");
        }

    }
}

int main()
{
    freopen ("cautbin.in","r",stdin);
    freopen ("cautbin.out","w",stdout);

    citire();
    solve();
    return 0;
}