Cod sursa(job #488701)

Utilizator gabipurcaruGabi Purcaru gabipurcaru Data 29 septembrie 2010 19:14:13
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.7 kb
// infoarena: problema/rmq //

#include <fstream>
#include <algorithm>
#include <cmath>
#define MAXN 100010
#define MAXM 1000010
using namespace std;

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

int rmq[20][MAXN],i,j,n,m,x[MAXN],a,b,k;

int main()
{
	in>>n>>m;
	
	for(i=1; i<=n; i++)
		in>>x[i], rmq[0][i]=i;
	
	for(j=1; (1<<j) <= n; j++)
		for(i=1; i + (1<<j) <= n+1; i++)
			if(x[rmq[j-1][i]] < x[rmq[j-1][i + (1<<(j-1))]])
				rmq[j][i] = rmq[j-1][i];
			else
				rmq[j][i] = rmq[j-1][i+(1<<(j-1))];
	
	for(i=1; i<=m; i++)
	{
		in>>a>>b;
		
		k=0;
		while(1<<(k+1) < b-a+1)
			k++;
		
		out << min(x[rmq[k][a]], x[rmq[k][b - (1<<k) +1]]) << '\n';
	}
	
	return 0;
}