Cod sursa(job #1051937)

Utilizator classiusCobuz Andrei classius Data 10 decembrie 2013 19:01:25
Problema Range minimum query Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
// 7.12.2013
// Range Minimium Query
// O(N) -> Pre-processing time
// O(sqrt(N)) -> Query time

using namespace std;

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

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

const int MAXN=1000;

int main(){
    int A[MAXN];
    int M[(int)sqrt(MAXN)];
    int N;

    // Pre-processing the array
    cin>>N;
    int k=sqrt(N);

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

    int j=0; //The counter for the parts of size sqrt(N)
    for(int i=0;i<N;i++){
        if(i==k*(j+1)){ //We have reached the next part of size sqrt(N)
            j++;
            M[j]=i;
        }else{
            if(A[M[j]]>A[i])
                M[j]=i;
        } //We are still in this part of size sqrt(N)
    }

    //The Query Part
    int K;
    cin>>K;

    for(int l=1;l<=K;l++){
        int x,y;
        cin>>x>>y;

        int mnm=x; //we set the minimum to something equivalent ot infinity

        int j=x/k;
        if(j<x) j++;
        int lf,rt;
        lf=k*j-1;
        rt=y/k+1;

        for(;(j+1)*k-1<=y;j++)// we search the whole parts of size sqrt(N) that are in the interval [x,y]
            if(A[mnm]>A[M[j]])
                mnm=M[j];

        for(int t=x;t<=lf;t++)// we search for the numbers that are at the edge of the interval [x,y]
            if(A[mnm]>A[t])
                mnm=t;

        for(int t=rt;t<=y;t++)
            if(A[mnm]>A[t])
                mnm=t;
        cout<<A[mnm]<<'\n';
    }



    return 0;
}