Cod sursa(job #2876884)

Utilizator demetriad-dagpagDavid Demetriad demetriad-dagpag Data 23 martie 2022 19:21:44
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <iostream>
#include <fstream>
#include <stdio.h>
#define LIM 1<<17
using namespace std;
char BUF[LIM];
int poz;

inline char getChar()
{
    poz++;
    if(poz>=LIM)
    {
        fread(BUF,LIM,1,stdin);
        poz=0;
    }
    return BUF[poz];
}

inline int getNr()
{
    int r=0, semn=1;
    char ch=getChar();
    while(isdigit(ch)==0 && ch!='-') ch=getChar();
    if(ch=='-')
    {
        semn=-1;
        ch=getChar();
    }
    while(isdigit(ch)!=0)
    {
        r=r*10+semn*(ch-'0');
        ch=getChar();
    }
    return r;
}
ofstream fout ("cautbin.out");
int v[100001];
int main()
{
    freopen("cautbin.in","r",stdin);
    int n, m, x, pas, j, q;
    n = getNr();
    for (int i=1;i<=n;i++)
    v[i]=getNr();
    m = getNr();
    for (int i=1;i<=m;i++) {
        q = getNr();
        x = getNr();
        if (q==0) {
                j=1;
            pas=1<<16;
            while (pas>0) {
                if (j+pas<=n && v[j+pas]<=x) {
                    j+=pas;
                }
                pas/=2;
            }
            if (v[j]==x)
                fout<<j<<endl;
            else
                fout<<-1<<endl;
        }
        else if (q==1) {
                j=1;
            pas=1<<16;
            while (pas>0) {
                if (j+pas<=n && v[j+pas]<=x) {
                    j+=pas;
                }
                pas/=2;
            }
            fout<<j<<endl;
        }
        else{
            j=1;
                pas=1<<16;
                while (pas>0) {
                    if (j+pas<=n && v[j+pas]<x) {
                        j+=pas;
                    }
            pas/=2;
            }
            fout<<j+1<<endl;
        }
    }
    return 0;
}