Cod sursa(job #3178328)

Utilizator 21CalaDarius Calaianu 21Cala Data 1 decembrie 2023 16:36:04
Problema Range minimum query Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>

#define NMAX 100005
#define NLOGMAX 17

using namespace std;
const string nume_fisier = "rmq";
ifstream fin(nume_fisier + ".in");
ofstream fout(nume_fisier + ".out");

int n, m, a[NMAX], mat[NMAX][NLOGMAX];

void preprocess()
{
    for (int i = 0; i < n; ++i)
        mat[i][0] = i;
    for (int j = 1; (1 << j) <= n; ++j)
    {
        for (int i = 0; i + (1 << j) - 1 <= n; ++i)
        {
            if (a[mat[i][j - 1]] < a[mat[i + (1 << (j - 1))][j - 1]])
                mat[i][j] = mat[i][j - 1];
            else
                mat[i][j] = mat[i + (1 << (j - 1))][j - 1];
        }
    }
}

int querry(int x, int y)
{
    int k = log(y - x + 1);
    return min(a[mat[x][k]], a[mat[y - (1 << k) + 1][k]]);
}

int main()
{
    fin >> n >> m;
    for (int i = 0; i < n; ++i)
        fin >> a[i];
    preprocess();
    for (int j = 0; j < m; ++j)
    {
        int x, y;
        fin >> x >> y;
        fout << querry(x - 1, y - 1) << '\n';
    }
}