Cod sursa(job #3313247)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 2 octombrie 2025 22:37:28
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <stdint.h>

const int32_t MAX_N = 100000;
const int32_t MAX_N_POW_2 = 1 << 16;

int32_t vec[MAX_N];

int main() {
	std::ifstream fin("cautbin.in");
	std::ofstream fout("cautbin.out");

	int32_t n;
	fin >> n;
	for(int32_t i = 0; i != n; ++i)
		fin >> vec[i];
	
	int32_t m;
	fin >> m;
	for(int32_t i = 0; i != m; ++i) {
		int32_t c, x;
		fin >> c >> x;

		if(c == 0) {
			int32_t pos = 0;
			for(int32_t step = MAX_N_POW_2; step; step >>= 1) {
				if(pos + step < n && vec[pos + step] <= x)
					pos += step;
			}
			if(vec[pos] == x) {
				fout << (pos + 1) << '\n';
			} else {
				fout << "-1\n";
			}
		} else if(c == 1) {
			int32_t pos = 0;
			for(int32_t step = MAX_N_POW_2; step; step >>= 1) {
				if(pos + step < n && vec[pos + step] <= x)
					pos += step;
			}
			
			fout << (pos + 1) << '\n';
		} else {
			int32_t pos = n;
			for(int32_t step = MAX_N_POW_2; step; step >>= 1) {
				if(pos >= step && vec[pos - step] >= x)
					pos -= step;
			}
			
			fout << (pos + 1) << '\n';
		}
	}

	fin.close();
	fout.close();

	return 0;
}