Cod sursa(job #2820839)

Utilizator DMR6476Erdic Dragos DMR6476 Data 21 decembrie 2021 18:24:19
Problema Range minimum query Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include<fstream>
#include<vector>
using namespace std;
ifstream fin("rmq.in");
ofstream fout("rmq.out");
int theMatrix[100005][20];
void PreCalc(vector<int> &theArray,int n)
{
    int maxPow=0;
    while( 1<< maxPow <= n)
        ++maxPow;
    for(int i=0; i<n; i++)
        theMatrix[0][i]=theArray[i];
    for(int i=1 ; i<= maxPow; i++)
        for(int j=0; j<n; j++)
            theMatrix[i][j]=min(theMatrix[i-1][j],theMatrix[i-1][j+1]);
}
int getQuery(int left,int right)
{
    int newN=right-left;
    int newPow=0;
    while((1<<newPow) <= newN)
    {
        ++newPow;
    }
    int firstVal=theMatrix[newPow-1][left];
    int secondVal=theMatrix[newPow-1][right-1<< (newPow-1)-1];

    return min(firstVal,secondVal);
}
int main()
{
    int n,queries;
    vector<int> theArray;
    fin>>n>>queries;
    theArray=vector<int> (n+1);
    for(int i=0; i<n; i++)
    {
        fin>>theArray[i];
    }
    int maxPow=0;
    while( 1<< maxPow <= n)
        ++maxPow;

    PreCalc(theArray,n);


    for(int i=0; i<queries; i++)
    {
        int x,y;
        fin>>x>>y;
        --x,--y;
        fout<<getQuery(x,y)<<"\n";
    }
    return 0;
}