Cod sursa(job #3286341)

Utilizator VespaOlaru Amelia Vespa Data 14 martie 2025 00:13:12
Problema Range minimum query Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
// RangeMinimumQuery.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <fstream>
using namespace std;
ifstream cin("rmq.in");
ofstream cout("rmq.out");
int n, m;
int lg[100001];
int a[100001][20];//a[i][j] = the minimum of the sequence starting from i with length j (where j is a power of 2)
//20 is roughly log2(100000)
const int inf = 0x3f3f3f3f;
int main()
{
    cin >> n >> m;
    for (int i = 0; i <= n + 1; i++)
        for (int j = 0; j <= n + 1; j++)a[i][j] = inf;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i][0];
    }
    
    //preprocessing log2(i) and p[i]=the biggest power of 2 <= i
    for (int i = 2; i <= n; i++)
        lg[i] = lg[i / 2] + 1;

    /*p[0] = 0; p[1] = 1; p[2] = 2;
    for (int i = 3; i <= n; i++)
        if (p[i] < p[i - 1] * 2)p[i] = p[i - 1];
        else
            p[i] = 2 * p[i - 1];*/

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

    //answering the queries
    for (int i = 0; i < m; i++)
    {
        int l, r; cin >> l >> r;
        if (l > r)swap(l, r);
        l--; r--;
        int len = r - l + 1;
        int k = 0;
        while ((1 << (k + 1)) < len)k++;
        cout << min(a[l][k], a[r - (1<<k) + 1][k]) << '\n';
        //cout << min(a[l][p[len]], a[r - (1<<(p[len])) + 1][p[len]]) << '\n';
    }


    return 0;
}