Cod sursa(job #2713170)

Utilizator davidcotigacotiga david davidcotiga Data 27 februarie 2021 12:56:57
Problema Range minimum query Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
#include <math.h>

#define MAXN 100005
#define MAXM 1000005

using namespace std;

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

int n, m;
int v[MAXN];

int mat[20][MAXN];

int main() {
	fin >> n >> m;

	for (int i = 0; i < n; ++i) {
		fin >> v[i];
		mat[0][i] = i;
	}

	//int putere = pow(2, 1);
	for (int i = 1; pow(2, i) <= n; ++i) {
		for (int j = 0; j < n - pow(2, i) + 1; ++j) {                    // get pow replaceD
			if (v[mat[i - 1][j]] < v[mat[i - 1][j + (int)pow(2, i - 1)]]) {
				mat[i][j] = mat[i - 1][j];
			}
			else
				mat[i][j] = mat[i - 1][j + (int)pow(2, i - 1)];
		}
	}


	int a, b;
	for (int i = 0; i < m; ++i) {
		int minim = 99999999;

		fin >> a >> b;
		a--;
		b--;

		int coloana = a;

		int len = b - a + 1;


		while (len > 0) {
			int exp = 0;
			int putere = 1;

			while (putere * 2 <= len) {
				putere *= 2;
				exp++;
			}

			//fout << exp << " " << coloana << "\n";
			if (minim > v[mat[exp][coloana]]) {
				minim = v[mat[exp][coloana]];
			}

			coloana += putere;
			len -= putere;

		}

		fout << minim << "\n";
	}

	return 0;
}