Cod sursa(job #2773808)

Utilizator francescom_481francesco martinut francescom_481 Data 8 septembrie 2021 18:57:29
Problema Range minimum query Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include<bits/stdc++.h>

using namespace std;

ifstream fin("rmq.in");
ofstream fout("rmq.out");
#define cin fin
#define cout fout

#define N 10005
int rmq[N][N], v[N], n, m, x, y;


int main()
{
    cin >> n >> m;
    for(int i = 1 ; i <= n ; i++)
    {
        cin >> v[i];
    }
    for(int i = 1 ; i <= n ; i++)
    {
        rmq[i][0] = v[i];
    }
    for(int j = 1, nr = 2 ; nr <= n ; j++ , nr *= 2)
    {
        for(int i = 1; i+nr-1 <= n ; i++)
        {
            rmq[i][j] = min(rmq[i][j-1],rmq[i+nr/2][j-1]);
        }
    }
    for(int i = 1 ; i <= m ; i++)
    {
        cin >> x >> y;
        if(x > y)swap(x,y);
        int d = y-x+1;
        int xp = 0, p = 1;
        while(p <= d)p *= 2, xp++;
        p /= 2 , xp--;
        cout << min(rmq[x][xp],rmq[y-p+1][xp]) << "\n";
    }
    return 0;
}