Cod sursa(job #2939940)

Utilizator IanisBelu Ianis Ianis Data 14 noiembrie 2022 15:27:42
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>

using namespace std;

#ifdef LOCAL
ifstream fin("input.txt");
#define fout cout
#else
ifstream fin("rmq.in");
ofstream fout("rmq.out");
#endif

const int NMAX = 1e5+5;
const int LOGN = 18;

int n, m;
int a[NMAX];
int dp[NMAX][LOGN];
int x, y;

void precalc() {
	for (int i = 1; i <= n; i++)
		dp[i][0] = i;
	for (int j = 1; (1 << j) <= n; j++)
		for (int i = 1; i + (1 << j) - 1 <= n; i++) {
			int p1 = dp[i][j - 1];
			int p2 = dp[i + (1 << (j - 1))][j - 1];
			dp[i][j] = a[p1] < a[p2] ? p1 : p2;
		}
}

int rmq(int i, int j) {
	int k = log2(j - i + 1);
	return min(
		a[dp[i][k]],
		a[dp[j - (1 << k) + 1][k]]
	);
}

int main() {
	fin >> n >> m;
	for (int i = 1; i <= n; i++)
		fin >> a[i];
	precalc();
	while (m--) {
		fin >> x >> y;
		fout << rmq(x, y) << '\n';
	}
	return 0;
}