Cod sursa(job #3170922)

Utilizator samyro14Samy Dragos samyro14 Data 18 noiembrie 2023 11:16:39
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("rmq.in");
ofstream fout("rmq.out");
const int maxn = 1e5 + 2;

int n, m;
int lg[maxn];
int a[maxn];
int rmq[20][maxn];
void read(){
   fin >> n >> m;
   for(int i = 1; i <= n; ++i){
       fin >> rmq[0][i];
   }
}

void precalculate(){
    for(int i = 2; i <= n; ++i)
        lg[i] = lg[i >> 1] + 1;
    for(int i = 1; i <= lg[n]; ++i){
        for(int j = 1; j <= n - (1 << i) + 1; ++j){
            rmq[i][j] = min(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]);
        }
    }
} 
int query(int st, int dr){
    if(st > dr)
        swap(st, dr);
    int l = lg[dr - st + 1];
    return min(rmq[l][st], rmq[l][dr - (1<<l) + 1]);
}

int main(){
    read();
    precalculate();
    for(int i = 1; i <= m; ++i){
        int x, y; fin >> x >> y;
        fout << query(x, y) << "\n";
    }
    return 0;
}
/*
rmq[i][j] = nodul care se afla pe nivelul minim in arbore, din secventa de lungime 2^i si care se termina
pe pozitia j
    
*/