Cod sursa(job #1364498)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 27 februarie 2015 18:16:43
Problema Range minimum query Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <cstdio>
#include <algorithm>

#define DIM 3666013
#define Nmax 100005
char buffer[DIM];
int poz = DIM - 1;

void Scanf(int &A){
    A = 0;
    while('0' > buffer[poz] || buffer[poz] > '9')
        if(++poz == DIM)
            fread(buffer,1,DIM,stdin),poz = 0;
    while('0' <= buffer[poz] && buffer[poz] <='9')
    {
        A = A * 10 + buffer[poz] - 48;
        if(++poz == DIM)
            fread(buffer,1,DIM,stdin),poz = 0;
    }
}

using namespace std;
int DP[17][Nmax],N,M;

void Read(){
    Scanf(N);
    Scanf(M);
    for(int i = 1; i <= N; ++i)
        Scanf(DP[0][i]);

}

void RMQ()
{
    int lim = 1,IT = 1;
    while(2*lim < N)
        lim *= 2;

    for(int i = 1; i <= lim; ++i)
    {
        for(int j = 1; j <= N; ++j)
            if(j + IT > N)
                DP[i][j] = DP[i-1][j];
            else
                DP[i][j] = min(DP[i-1][j],DP[i-1][j+IT]);
        IT *= 2;
    }
}

int Querry(int x,int y)
{
    int lim = 1,lg = y - x + 1,pz = 0;
    while(2*lim < lg)
        lim *= 2,++pz;
    return min(DP[pz][x],DP[pz][x+lg-lim]);
}

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

    Read();
    RMQ();
    int x,y;
    for(int i = 1; i <= M; ++i)
    {
        Scanf(x),Scanf(y);
        printf("%d\n",Querry(x,y));
    }

    return 0;
}