Cod sursa(job #2430439)

Utilizator katanau26@yahoo.comIonut Barbu [email protected] Data 14 iunie 2019 21:36:55
Problema Range minimum query Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
#include <cmath>
#define MAXN 100001
#define MAXIND 1<<(int(log2(MAXN)) + 2)

using namespace std;

int M[MAXIND], A[MAXN], N, Q;// A[MAXN] = {2, 4, 3, 1, 6, 7, 8, 9, 1, 7}, N = 10;
ifstream fin("rmq.in");
ofstream fout("rmq.out");

void initialize(int node, int st, int dr)
{
    if (st == dr)
        M[node] = st;
    else
    {
        //compute the values in the left and right subtrees
        initialize(2 * node, st, (st + dr) / 2);
        initialize(2 * node + 1, (st + dr) / 2 + 1, dr);

        //search for the minimum value in the first and second half of the interval
        if (A[M[2 * node]] <= A[M[2 * node + 1]])
            M[node] = M[2 * node];
        else
            M[node] = M[2 * node + 1];
    }
}

int query(int node, int st, int dr, int a, int b)
{
    int p1, p2;

    //if the current interval doesn't intersect the query interval return -1
    if (a > dr || b < st)
        return -1;

    //if the current interval is included in the query interval return M[node]
    if (st >= a && dr <= b)
        return M[node];

    //compute the minimum position in the left and right part of the interval
    p1 = query(2 * node, st, (st + dr) / 2, a, b);
    p2 = query(2 * node + 1, (st + dr) / 2 + 1, dr, a, b);

    //return the position where the overall minimum is
    if (p1 == -1)
        return p2;

    if (p2 == -1)
        return p1;

    if (A[p1] <= A[p2])
        return p1;

    return p2;
}

int main()
{
    int a, b, i;

    fin>>N>>Q;
    for (i = 1; i <= N; i++)
        fin>>A[i];

    initialize(1, 1, N);

    for (i = 1; i <= Q; i++)
    {
        fin>>a>>b;
        fout<<A[query(1, 1, N, a, b)]<<"\n";
    }

    return 0;
}