Cod sursa(job #2398573)

Utilizator StasBrega Stanislav Stas Data 5 aprilie 2019 19:05:32
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>

using namespace std;

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};

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

int i,N,M,a[100005],logN,lg;

int main()
{

    fin >> N;

    for(i=1;i<=N;i++)
        fin >> a[i];

    for(logN=1;logN<=N;logN<<=1);

    fin >> M;

    for(;M;M--)
    {
        int t,x;
        fin >> t >> x;
        if(t<2)
        {
            for(lg=logN,i=0;lg;lg>>=1)
                if(i+lg<=N and a[i+lg]<=x)
                    i+=lg;
            if(t==0 and a[i]!=x)
                fout << "-1" << endl;
            else
                fout << i << endl;
        }
        else
        {
            for(lg=logN,i=N;lg;lg>>=1)
                if(i-lg>=1 and a[i-lg]>=x)
                    i-=lg;
            fout << i << endl;
        }
    }

    return 0;

}