Cod sursa(job #947456)

Utilizator BitOneSAlexandru BitOne Data 7 mai 2013 16:03:01
Problema Range minimum query Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <cstdlib>
#include <fstream>

using namespace std;

const int NMAX = 100011;
const int LOG2NMAX = (1 << 18) | 1;

int rmq[LOG2NMAX][NMAX];

inline int min(int x, int y) {return x <= y ? x : y;}
constexpr int log2(int N)
{
#ifdef __GNUC__
    return 8 * sizeof(N) - 1 - __builtin_clz(N);
#else
    int count = -1;
    for(; N; N >>= 1, ++count);
    return count;
#endif // __GNUC__
}

int main()
{
    int N, log2N, M, i, j, till, x, y, len, toAdd;
    ifstream in("rmq.in");
    ofstream out("rmq.out");

    in >> N >> M;
    for(i = 1; i <= N; ++i)
        in >> rmq[0][i];
    log2N = log2(N);
    for(i = 1; i <= log2N; ++i)
    {
        toAdd = 1 << (i - 1);
        till = N - (toAdd << 1) + 1;
        for(j = 1; j <= till; ++j)
            rmq[i][j] = min(rmq[i - 1][j], rmq[i - 1][j + toAdd]);
    }
    for(; M; --M)
    {
        in >> x >> y;
        len = log2(y - x + 1);
        out << min(rmq[len][x], rmq[len][y - (1 << len) + 1]) << '\n';
    }

    return EXIT_SUCCESS;
}