Cod sursa(job #2541148)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 8 februarie 2020 10:26:40
Problema Range minimum query Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("rmq.in");
ofstream fout("rmq.out");
const int MAXN = 100010, MAXL = 20, INF = 0x3f3f3f3f;

int rmq[MAXL][MAXN], lg[MAXN], n;

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

int query(int x, int y)
{
    int res = INF;
    for (int i = lg[y - x]; i >= 0 && x <= y; --i)
        if (x + (1 << i) - 1 <= y)
            res = min(res, rmq[i][x]), x += (1 << i);
    return res;
}

int main()
{
    int m;
    fin >> n >> m;
    for (int i = 1; i <= n; ++i)
        fin >> rmq[0][i];
    preprocess();
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        fout << query(x, y) << '\n';
    }
    return 0;
}