Cod sursa(job #2175152)

Utilizator DanielRusuDaniel Rusu DanielRusu Data 16 martie 2018 15:41:44
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <cstdio>

using namespace std;

#define DIM 100004

int pw[DIM], dp[DIM][20], N, M;

int main() {
    freopen("rmq.in","r",stdin);
    freopen("rmq.out","w",stdout);

    scanf("%d %d\n", &N, &M);

    int p = 1, depus = 0;
    for(int i = 1; i <= N; ++i) {
        scanf("%d\n", &dp[i][0]);
        if(2 * p <= i) {
            p <<= 1;
            depus++;
        }

        pw[i] = depus;
    }

    for(int lg = 2, j = 1; lg <= N; lg *= 2, j++) {
        for(int i = 1; i <= N; ++i) {
            dp[i][j] = min(dp[i][j - 1], dp[min(i + lg / 2, N - (1 << (j - 1)) + 1)][j - 1]);
        }
    }

    while(M--) {
        int x, y;

        scanf("%d %d\n", &x, &y);

        cout << min(dp[x][pw[y - x + 1]], dp[y - (1 << pw[y - x + 1]) + 1][pw[y - x + 1]]) << '\n';
    }

    return 0;
}