Cod sursa(job #1437378)

Utilizator andreirulzzzUPB-Hulea-Ionescu-Roman andreirulzzz Data 17 mai 2015 16:06:36
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <cmath>
#define NMAX 100001
#define HMAX 17
using namespace std;

int min(int a, int b) {
	if (a < b) return a;
	return b;
}

int main() {
	int N, M;
	int **a;

	a = (int **)calloc(NMAX, sizeof(int *));
	for (int i = 0; i < NMAX; i++)
		a[i] = (int *)calloc(HMAX, sizeof(int));

	freopen("rmq.in", "r", stdin);
	freopen("rmq.out", "w", stdout);

	scanf("%d %d", &N, &M);
	for (int i = 0; i < N; i++)
		scanf("%d", &a[i][0]);

	/* init */

	int msb = 0;
	for (int i = 1; i < 17; i++)
		if ((N & (1 << i))) msb = i;
	++msb;
	
	for (int t = 1; t < msb; ++t) {
		int dist = 1 << t;
		for (int i = 0; i < N; i++)
			if (i + dist > N) {
				if (i < N - 1)
					a[i][t] = min(a[i][t - 1], a[i + 1][t - 1]);
				else
					a[i][t] = a[i][t - 1];
			}
			else {
				a[i][t] = min(a[i][t - 1], a[i + dist / 2][t - 1]);
			}
			
	}

	int x, y;
	while (M--) {
		scanf("%d%d", &x, &y);
		--x; --y;
		int dif = y - x;
		int l = (int)log2(dif);
		printf("%d\n", min(a[x][l], a[y - (1 << l) + 1][l]));
	}

	return 0;
}