Cod sursa(job #1537414)

Utilizator BaweeLazar Vlad Bawee Data 27 noiembrie 2015 11:18:24
Problema Range minimum query Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
#include <cmath>

using namespace std;

ifstream f("rmq.in");
ofstream g("rmq.out");

int A[101],M[101][101],N;
const int ZERO = 1e9 + 1;

int main()
{
    int i,j,q,L,R;

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

    for(i = 0; i < N; i++)
          M[i][0] = i;

   int k = log2(N);
   for(j = 1; j <= k; j++)
        for(i = 0; i <= N - (1 << j); i++)
            M[i][j] = min(M[i][j - 1], M[i + (1 << (j - 1))][j - 1]);

    f >> q; // number of queries
    for( i = 0; i < q; i++)
    {
        f >> L >> R; // boundaries of next query, 0-indexed
        int answer = ZERO;
        for( j = k; j >= 0; j--)
        {
            if(L + (1 << j) - 1 <= R)
            {
                answer = min(answer, M[L][j]);
                L += 1 << j; // instead of having L', we increment L directly
            }
        }
        g << answer + 1 << "\n";
    }

    return 0;
}