Cod sursa(job #2608923)

Utilizator Vlad_AnicaAnica-Popa Vlad-Ioan Vlad_Anica Data 1 mai 2020 21:19:29
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");

int v[100001];

int main()
{
    int m,x,n,i,step,pos,mj,st,dr,c;
    fin >> n;
    for(i=1;i<=n;i++)
        fin >> v[i];

    fin >> m;
    for(i=1;i<=m;i++)
    {
        fin >> c >> x;
        if  (c==0 || c==1)
        {
            pos=0;
            step=65536;
            while(step>0)
            {
                if(step+pos<=n && v[step+pos]<=x)
                    pos+=step;
                step=step>>1;
            }
            if(c==0)
            {
                if(v[pos]==x)
                    fout << pos << '\n';
                else
                    fout << -1 << '\n';
            }
            else
            {
                fout << pos << '\n';
            }


        }
        else
        {
                dr=n;
                st=1;
                mj=1;
                while(st<dr)
                {
                    mj=(st+dr)>>1;
                    if(v[mj]<x)
                    {
                        st=mj+1;
                    }
                    else
                    {
                        dr=mj;
                    }
                }
                while(v[mj]<x)
                    mj++;

                fout << mj << '\n';

            }
        }


    return 0;
}