Cod sursa(job #2893458)

Utilizator pedrosanchez2pedro sanchez pedrosanchez2 Data 25 aprilie 2022 22:20:20
Problema Range minimum query Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <array>
#include <math.h>

using namespace std;

/*ifstream in("input.txt");
ofstream out("output.txt");*/

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

int mat[100002][18];
int main()
{
    int n, m;
    in >> n >> m;
    array<int, 100001> a{};
    int l[100002];
    l[1] = 0;
    for (int i = 2; i <= n; ++i)
        l[i] = l[i / 2] + 1;

    for (int i = 0; i < n; ++i)
        in >> a[i];
    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];
    for (int i = 0; i < m; ++i)
    {
        int x, y;
        in >> x >> y;
        --x, --y;
        int lg = l[(y - x + 1)];
        //cout << min(mat[x][lg], mat[y - (1 << lg) + 1][lg]) + 1<< endl;
        out << min(a[mat[x][lg]], a[mat[y - (1 << lg) + 1][lg]]) << endl;
    }
}