Cod sursa(job #542906)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 27 februarie 2011 10:07:09
Problema Range minimum query Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
///RMQ <N log N, 1>
/// Folositor atunci cand avem multe queryuri
#include <stdio.h>
#include <iostream>

using namespace std;

int N, M;
const int nmax = 100100;
int RMQ[nmax][20], A[nmax], lg[nmax];

void read()
{

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

    scanf("%d %d",&N,&M);
    int i;
    for(i = 0; i < N; i++)
        scanf("%d",&A[i]);

}

void precalc()
{
    // Precalculam logaritmu
    lg[1] = 0;
    int i;
    for(i = 2; i <= N; i++)
        lg[i] = lg[i >> 1] + 1;
}

void construct()
{
    int i, j;
    for(i = 0; i < N; i++)
        RMQ[0][i] = A[i];

    for(j = 1; (1 << j) <= N; j++)
        for(i = 0; i + (1 << j) - 1 < N; i++)
            RMQ[j][i] = min(RMQ[j - 1][i], RMQ[j - 1][i + (1 << (j - 1))]);
}

void query()
{
    int i, a, b, log;
    for(i = 1; i <= M; i++)
    {
        scanf("%d %d",&a,&b);
        a--;b--;
        log = lg[b - a + 1];
        printf("%d\n",min(RMQ[log][a], RMQ[log][b - (1 << log) + 1]));
    }
}


int main()
{
    read();
    precalc();
    construct();
    query();
    return 0;
}