Cod sursa(job #1293274)

Utilizator StarGold2Emanuel Nrx StarGold2 Data 15 decembrie 2014 17:53:21
Problema Range minimum query Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
using namespace std;

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

long long n, m, i, j, k, ok;
long long a[20][100001], val;
long long v[1000001], x, y, p;

int main(){
	fin >> n >> m;
	for(i = 1; i <= n; i ++)
		fin >> a[0][i];
	for(i = 1; (1 << i) <= n; i ++){
		for(j = 1; j <= n; j ++){
			a[i][j] = a[i - 1][j];
			if(j + (1 << (i - 1)) <= n){
				if(a[i - 1][j + (1 << (i - 1))] < a[i][j])
					a[i][j] = a[i - 1][j + (1 << (i - 1))];
			}
		}
	}
	for(i = 2; i <= n; i ++){
		v[i] = 1 + v[i / 2];
	}
	for(i = 1; i <= m; i ++){
		fin >> x >> y;
		p = v[y - x + 1];
		val = a[p][x];
		if(val > a[p][y - p])
			val = a[p][y - p];
		fout << val << "\n";
	}
	return 0;
}