Cod sursa(job #2864354)

Utilizator albuAlbu Victor albu Data 7 martie 2022 20:03:36
Problema Range minimum query Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
using namespace std;
#define MAX 500
ifstream in("rmq.in");
ofstream out("rmq.out");
int lookup[MAX][MAX];
const int NMAX=1e5+1;
const int MMAX=1e6+1;
int a[NMAX];
struct Query {
	int L, R;
}q[MMAX];
void preprocess(int arr[], int n)
{
	for (int i = 0; i < n; i++)
		lookup[i][0] = i;
	for (int j = 1; (1 << j) <= n; j++)
	{
		for (int i = 0; (i + (1 << j) - 1) < n; i++)
		{
			if (arr[lookup[i][j - 1]]< arr[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];
		}
	}
}
int query(int arr[], int L, int R)
{
	int j = (int)log2(R - L + 1);
	if (arr[lookup[L][j]]<= arr[lookup[R - (1 << j) + 1][j]])
		return arr[lookup[L][j]];
	else
		return arr[lookup[R - (1 << j) + 1][j]];
}
void RMQ(int arr[], int n, Query q[], int m)
{
	preprocess(arr, n);
	for (int i = 0; i < m; i++)
	{
		int L = q[i].L, R = q[i].R;
		out<<query(arr, L, R)<<endl;
	}
}
int main()
{

	int n,m;
	in>>n>>m;
	for(int i=0;i<n;i++)
        in>>a[i];
	for(int i=0;i<m;i++)
    {
        int st,dr;
        in>>st>>dr;
        q[i].L=st-1;
        q[i].R=dr-1;

    }
	RMQ(a, n, q, m);
	return 0;
}