Cod sursa(job #1390121)

Utilizator BogdanisarBurcea Bogdan Madalin Bogdanisar Data 16 martie 2015 21:17:49
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include<iostream>
#include<fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int N,M,i,j,poz;
int v[100002];

int bs(int);

int main()
{
    f>>N;
    for (i=1;i<=N;++i)
        f>>v[i];
    f>>M;
    for (j=0;j<M;++j)
    {
        int op,x;
        f>>op>>x;
        poz=bs(x);
        //cout<<poz<<' ';
        if (op==0)
        {
            if (v[poz]==x)
            {
                while (v[poz+1]==x)
                    ++poz;
                g<<poz<<'\n';
            }
            else
                g<<-1<<'\n';
        }
        else if (op==1)
        {
            if (v[poz]==x)
            {
                while(v[poz+1]==x)
                    ++poz;
                g<<poz<<'\n';
            }
            else
            {
                while (v[poz]>x)
                    --poz;
                g<<poz<<'\n';
            }
        }
        else
        {
            if (v[poz]==x)
            {
                while(v[poz-1]==x)
                    --poz;
                g<<poz<<'\n';
            }
            else
            {
                while (v[poz]<x)
                    ++poz;
                g<<poz<<'\n';
            }
        }
    }
    f.close();g.close();
    return 0;
}


int bs(int val)
{
    int poz,put;
    for (put=1;put<=N;put<<=1);
    put>>=1;
    for (poz=0;put;put>>=1)
        if (poz+put<=N && v[poz+put]<=val)
            poz+=put;
    return poz;
}