Cod sursa(job #3344002)

Utilizator bogdan1479Luca Bogdan Alexandru bogdan1479 Data 28 februarie 2026 23:19:42
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>

using namespace std;

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

const int NMAX = 1e5 + 1, LOGMAX = 20;

int n, m;

int t[LOGMAX][NMAX], log2[NMAX];

void citire() {
    fin >> n >> m;
    log2[0] = -1;

    for(int i = 1; i <= n; ++i) {
        fin >> t[0][i];
        log2[i] = log2[i >> 1] + 1;
    }
}

void genRMQ() {
    for(int i = 1, lg = 2; lg <= n; ++i, lg <<= 1) {
        for(int j = 1; j + lg - 1 <= n; ++j) {
            t[i][j] = min(t[i - 1][j], t[i - 1][j + lg / 2]);
        }
    }
}

int query(int x, int y) {
    int k = log2[y - x + 1], lg = (1 << k);
    return min(t[k][x], t[k][y - lg + 1]);
}

void solutie() {
    int x, y;

    while(m--) {
        fin >> x >> y;
        fout << query(x, y) << '\n';
    }
}

int main() {
    citire();
    genRMQ();
    solutie();

    return 0;
}