Cod sursa(job #2820923)

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

    if(firstVal < 0)
        return secondVal;
    else if(secondVal < 0)
        return firstVal;
    return min(firstVal,secondVal);
}
int theArray[100005];
int main()
{

    int n,queries;
    fin>>n>>queries;


    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;
}