Cod sursa(job #3191536)

Utilizator PsyDuck1914Feraru Rares-Serban PsyDuck1914 Data 9 ianuarie 2024 21:36:47
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb

#include <bits/stdc++.h>
using namespace std;

#define MAX 100000

ifstream f ("rmq.in");
ofstream g ("rmq.out");

int lookup[MAX+1][17];
int v[MAX+1];

// Fills lookup array lookup[][] in bottom up manner.
void buildSparseTable(int arr[], int n)
{
	// Initialize M for the intervals with length 1
	for (int i = 0; i < n; i++)
		lookup[i][0] = arr[i];

	// Compute values from smaller to bigger intervals
	for (int j = 1; (1 << j) <= n; j++) {

		// Compute minimum value for all intervals with
		// size 2^j
		for (int i = 0; (i + (1 << j) - 1) < n; i++) {

			// For arr[2][10], we compare arr[lookup[0][7]] 
			// and arr[lookup[3][10]]
			if (lookup[i][j - 1] < 
						lookup[i + (1 << (j - 1))][j - 1])
				lookup[i][j] = lookup[i][j - 1];
			else
				lookup[i][j] = 
						lookup[i + (1 << (j - 1))][j - 1];
		}
	}
}

// Returns minimum of arr[L..R]
int query(int L, int R)
{
	
	int j = (int)log2(R - L + 1);

	// Compute minimum of last 2^j elements with first
	// 2^j elements in range.
	// For [2, 10], we compare arr[lookup[0][3]] and
	// arr[lookup[3][3]],
	if (lookup[L][j] <= lookup[R - (1 << j) + 1][j])
		return lookup[L][j];

	else
		return lookup[R - (1 << j) + 1][j];
}

// Driver program
int main()
{
	int n, q;
	f >> n >> q;
	for(int i=0; i<n; i++)
	    f >> v[i];
	
	buildSparseTable(v, n);
	
	for(int i=1; i<=q; i++){
	    int x, y;
	    f >> x >> y;
	    g << query(x-1, y-1) << "\n";
	}
	
	return 0;
}