Cod sursa(job #1051984)

Utilizator classiusCobuz Andrei classius Data 10 decembrie 2013 19:38:22
Problema Range minimum query Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
// 8.12.2013
// Range Minimum Query
// <O(N logN)> Pre-processing time
// <O(1)> Query time
// Method: We will build using dynamic programming a matrix where I keep
//the indexes of sequence that has the lenght a power of 2

using namespace std;

#include<fstream>
#include<cmath>
#include<algorithm>

ifstream cin("rmq.in");
ofstream cout("rmq.out");

const int MAXN=1000;
int A[MAXN];
int M[MAXN][MAXN];

int main(){
    int N;
    int Q;

    cin>>N>>Q;
    for(int i=0;i<N;i++)
        cin>>A[i];

    // The pre-processing part
    // I build a matrix M where M[i][j] is the index of the
    //minimum element in the sequence that starts at i and has 2^j elements

    for(int i=0;i<N;i++)
        M[i][0]=i; // The base case

    for(int j=1;1<<j<=N ;j++)
        for(int i=0;i+(1<<(j-1))-1<N;i++){
            if(A[M[i][j-1]] > A[M[i+(1<<(j-1))][j-1]])
                M[i][j]=M[i+(1<<(j-1))][j-1];
            else
                M[i][j]=M[i][j-1];
        }

    // The Query part



    while(Q--){
        int x,y,k;
        cin>>x>>y;
        x--; y--;
        k=(int)(log(y-x+1.0)/log(2.0)); // Now I can answer the queries in linear time
        cout<<min(A[M[x][k]],A[M[y-(1<<k)+1][k]])<<'\n';
    }

    return 0;
}