Cod sursa(job #3251760)

Utilizator Langa_bLanga Radu Langa_b Data 26 octombrie 2024 19:32:40
Problema Range minimum query Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
//ifstream cin("rmq.in");
//ofstream cout("rmq.out");
int n, v[100002], rmq[100002][30], q, put[100002];
int main() {
	cin >> n >> q;
	for (int i = 1; i <= n; i++) {
		cin >> v[i];
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 0; j < 29; j++) {
			rmq[i][j] = 1e9;
		}
	}
	put[1] = 0;
	put[2] = 1;
	int pw = 2, cnt = 1;
	for (int i = 3; i <= n; i++) {
		if (pw * 2 <= i) {
			pw *= 2;
			cnt++;
		}
		put[i] = cnt;
	}
	for (int j = 0, lg = 1; lg <= n; j++, lg *= 2) {
		for (int i = 1; i <= n - lg + 1; i++) {
			if (j == 0) {
				rmq[i][j] = v[i];
			}
			else {
				rmq[i][j] = min(rmq[i][j - 1], rmq[i + lg / 2][j - 1]);
			}
		}
	}
	int putere;
	int a, b, ans;
	for (int i = 1; i <= q; i++) {
		cin >> a >> b;
		putere = put[b - a + 1];
		ans = min(rmq[a][putere], rmq[b - (1 << putere)+1][putere]);
		cout << ans << '\n';
	}
}