Cod sursa(job #3219280)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 30 martie 2024 16:45:16
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <stdint.h>

int32_t min(int32_t x, int32_t y) {
	return (x < y) ? x : y;
}
int32_t log2(int32_t n) {
	n |= n >> 1;
	n |= n >> 2;
	n |= n >> 4;
	n |= n >> 8;
	n |= n >> 16;

	n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1);
	n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2);
	n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4);
	n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8);
	n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16);

	return n - 1;
}

const int32_t MAX_N = 100000;
const int32_t MAX_N_LOG_2 = 17;

int32_t rmq[MAX_N_LOG_2][MAX_N];
int main() {
	std::ifstream fin("rmq.in");
	std::ofstream fout("rmq.out");

	int32_t n, m;
	fin >> n >> m;

	for(int32_t i = 0; i != n; ++i)
		fin >> rmq[0][i];
	
	int32_t nLog2 = log2(n);
	for(int32_t i = 1; i <= nLog2; ++i) {
		int32_t len = 1 << i, prevLen = 1 << (i - 1);
		for(int32_t j = 0; j != n - len + 1; ++j)
			rmq[i][j] = min(rmq[i - 1][j], rmq[i - 1][j + prevLen]);
	}

	for(int32_t i = 0; i != m; ++i) {
		int32_t x, y;
		fin >> x >> y;
		--x; --y;
		int32_t len = y - x + 1;
		int32_t lenLog2 = log2(len);
		int32_t lenPow2 = 1 << lenLog2;

		fout << min(rmq[lenLog2][x], rmq[lenLog2][x + len - lenPow2]) << '\n';
	}

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

	return 0;
}