Cod sursa(job #2464945)

Utilizator HumikoPostu Alexandru Humiko Data 29 septembrie 2019 10:49:07
Problema Range minimum query Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <algorithm>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <cstring>

using namespace std;

//#include <iostream>
#include <fstream>

//ifstream cin ("input.in");
//ofstream cout ("output.out");

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

static const int NMAX = 1e5+5;

int v[NMAX];
int logarithm[NMAX];
int dp[NMAX][32];

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	int n, m;
	cin>>n>>m;

	for ( int i = 1; i <= n; ++i ) {
		cin>>v[i];
	}

	for ( int i = 2; i <= n; ++i ) {
		logarithm[i] = logarithm[i/2]+1;
	}

	for ( int i = 0; i <= n; ++i ) {
		dp[i][0] = min(v[i], v[i+1]);
	}

	for ( int i = 1; i <= logarithm[n]; ++i ) {
		for ( int j = 1; j <= n; ++j ) {
			if ( j+(1<<i) > n ) {
				break;
			}

			dp[j][i] = min(dp[j][i-1], dp[j+(1<<(i-1))][i-1]);
		}
	}

	for ( int i = 1; i <= m; ++i ) {
		int a, b;
		cin>>a>>b;

		if ( a == b ) {
			cout<<v[a];
		}
		else {
			if ( a > b ) {
				swap(a, b);
			}

			cout<<min(dp[a][logarithm[b-a]], 
					  dp[b-(1<<logarithm[b-a])][logarithm[b-a]]);
			cout<<'\n';
		}
	}
}