Cod sursa(job #3263280)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 14 decembrie 2024 09:56:43
Problema Range minimum query Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
using namespace std;

int rmq[100005][17]; // 2^17 > 100000 => ne ajung puterile de la 0 la 16
int n, m, x, y;
int p2[100005]; // p2[i] = cea mai apropiata putere a lui 2 de i <= 

void read() {
    cin >> n >> m;
    for (int i=1;i<=n;i++) {
        cin >> rmq[i][0];
    }
    p2[1] = 0;
    for (int i=2;i<=n;i++) {
        p2[i] = p2[i-1];
        if ((1<<(p2[i]+1)) <= i) {
            p2[i]++;
        }
    }
}

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


int main() {
    freopen("rmq.in", "r", stdin);
    freopen("rmq.out", "w", stdout);
    read();
    create();
    for (int t=1;t<=m;t++) {
        cin >> x >> y;
        int l = (y-x+1);
        cout << min(rmq[x][p2[l]], rmq[y-(1<<p2[l])+1][p2[l]]) << '\n';
    }
    return 0;
}