Cod sursa(job #3155103)

Utilizator BurloiEmilAndreiBurloi Emil Andrei BurloiEmilAndrei Data 7 octombrie 2023 12:43:18
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e5 + 5, LOGN = 20 + 5;

int v[MAXN], sparseTable[MAXN][LOGN];

void buildSparseTable(int n) {
    int i, lin, col;

    for(i = 0; i < n; i++){
        sparseTable[i][0] = v[i];
    }

    for(col = 1; col <= log2(n); col++){
        for(lin = 0; (lin + (1 << col) - 1) < n; lin++){
            sparseTable[lin][col] = min(sparseTable[lin][col - 1], sparseTable[lin + (1 << (col - 1))][col - 1]);
        }
    }

}

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

int main() {
    ifstream cin("rmq.in");
    ofstream cout("rmq.out");

    int n, m, i, x, y;

    cin >> n >> m;
    for(i = 0; i < n; i++){
        cin >> v[i];
    }

    buildSparseTable(n);

    for(i = 0; i < m; i++){
        cin >> x >> y;
        cout << query(x - 1, y - 1) << '\n';
    }


    return 0;
}