Cod sursa(job #2820907)

Utilizator DMR6476Erdic Dragos DMR6476 Data 21 decembrie 2021 20:39:39
Problema Range minimum query Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
ifstream fin("rmq.in");
ofstream fout("rmq.out");
int theMatrix[20][100005];
int getQuery(int l,int r)
{
    int theValue=r-l;
    int maxPow=0;
    while((1 << maxPow) <= theValue )
        ++maxPow;
    --maxPow;
    int firstVal=theMatrix[maxPow][l];
    int secondVal=theMatrix[maxPow][r-(1<< maxPow)+1];

    return min(firstVal,secondVal);
}
int main()
{

    int n,queries;
    fin>>n>>queries;
    vector<int> theArray;
    theArray=vector<int> (n+1);

    for(int i=0; i<n; i++)
        fin>>theArray[i];
    int maxPower=0;
    while( (1<< maxPower) <= n)
        ++maxPower;
    for(int i=0; i<=n; i++)
        theMatrix[0][i]=theArray[i];
    for(int i=1; i<=maxPower; i++)
    {
        //ma duc la fiecare putere a lui 2
        for(int j=0; j<n-(1<<i)+1; j++)
            theMatrix[i][j]=min(theMatrix[i-1][j],theMatrix[i-1][j+(1<<(i-1))]);
    }
    for(int i=0; i<queries; i++)
    {
        int x,y;
        fin>>x>>y;
        --x,--y;
        fout<<getQuery(x,y)<<"\n";

    }
    return 0;
}