Cod sursa(job #3200607)

Utilizator Radu_BicliBiclineru Radu Radu_Bicli Data 5 februarie 2024 12:23:06
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("rmq.in");
ofstream fout("rmq.out");
int n, q, i, j, lg[100002];
int a[20][100002], x, y;

static inline int Query(int st, int dr) {
    int k = lg[dr - st];
    return min(a[k][st], a[k][dr - (1 << k) + 1]);
}

int main() {
    fin >> n >> q;
    for(i = 2; i <= n; i++) lg[i] = lg[i / 2] + 1;

    for(i = 1; i <= n; i++) fin >> a[0][i];

    for(i = 1; i <= lg[n]; i++) {
        for(j = 1; j <= n - (1 << i) + 1; j++) {
            a[i][j] = min(a[i - 1][j], a[i - 1][j + (1 << (i - 1))]);
        }
    }

    while(q--) {
        fin >> x >> y;
        fout << Query(x, y) << "\n";
    }

    return 0;
}