Cod sursa(job #3124197)

Utilizator JohnnyFortaPascu Ioan JohnnyForta Data 27 aprilie 2023 11:08:23
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;

int rmq[100000][17], n, m;
ifstream f("rmq.in");
ofstream out("rmq.out");

void readNums(){
    for(int i = 0; i < n; i++){
        f>>rmq[i][0];
    }
}

void populateRmq(){
    for(int i = 1; i <= int(log2(n)); i++){
        for(int j = 0; j < n - int(pow(2, i - 1)); j++){
            int fhalf = rmq[j][i - 1], shalf = rmq[j + int(pow(2, i - 1))][i - 1];
            if(fhalf < shalf){
                rmq[j][i] = fhalf;
            }else{
                rmq[j][i] = shalf;
            }
        }
    }
}

int query(int f, int l){
    int len = l - f + 1;
    int ind = int(log2(len));
    int fnum = rmq[f][ind], snum = rmq[l-int(pow(2,ind)) + 1][ind];
    if(fnum < snum){
        return fnum;
    }
    return snum;
}

int main(){
    int a, b;
    f>>n>>m;
    readNums();
    populateRmq();
    for(int i = 0; i < m; i++){
        f>>a>>b;
        a--;
        b--;
        out<<query(a,b)<<endl;
    }
    f.close();
    out.close();
}