Cod sursa(job #3291869)

Utilizator radugheoRadu Mihai Gheorghe radugheo Data 5 aprilie 2025 22:05:01
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <cmath>

using namespace std;

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

int n, m, a, b;
int v[100005];
int M[100005][20];

int main(){
    fin >> n >> m;
    for (int i=0; i<n; i++){
        fin >> v[i];
        M[i][0] = i;
    }
    /*log2[1] = 0;
    for (int i=2; i<n; i++){
        log2[i] = log2[i/2] + 1;
    }*/
    for (int j=1; (1 << j) <= n; j++){
        for (int i=0; i + (1 << j) <= n; i++){
            int first_half_position = M[i][j - 1];
            int second_half_position = M[i + (1 << (j - 1))][j - 1];
            if (v[first_half_position] <= v[second_half_position]){
                M[i][j] = first_half_position;
            }
            else{
                M[i][j] = second_half_position;
            }
        }
    }
    while (m--){
        fin >> a >> b;
        a--, b--;
        int k = log2(b - a + 1);
        fout << min(v[M[a][k]], v[M[b - (1 << k) + 1][k]]) << '\n';
    }
    return 0;
}