Cod sursa(job #3340911)

Utilizator g.vladGociu Vlad g.vlad Data 17 februarie 2026 09:27:38
Problema Range minimum query Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb

// #include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

std::ifstream in("rmq.in");
std::ofstream out("rmq.out");

#define SIZE 100001
#define LG_SIZE 20
#define type unsigned

unsigned lg[SIZE];
unsigned dp[LG_SIZE][SIZE];

/// uses 0-indexing
inline void rmq_init(type const* const range, size_t const length) {
    lg[1] = 0;

    for(unsigned i = 2; i <= length; i += 1) {
        lg[i] = lg[i >> 1] + 1;
        // std::cout << lg[i] << ' ';
    }
    // std::cout << '\n';

    std::memcpy(dp[0], range, length * sizeof(type));

    for(unsigned pow = 1; pow <= LG_SIZE; pow += 1) {
        unsigned start;
        for(start = 0; start + (1 << (pow - 1)) < length; start += 1) {
            dp[pow][start] = std::min(
                dp[pow - 1][start + (1 << (pow - 1))],
                dp[pow - 1][start]
            );
        }
        for(; start < length; start += 1) {
            dp[pow][start] = dp[pow - 1][start];
        }
    }

    // for(unsigned i = 2; i <= length; i += 1) {
    //     std::cout << lg[i] << ' ';
    // }
    // std::cout << '\n';
}

inline type rmq_query(unsigned const start, unsigned const finish) {
    // std::cout << "Printing " << start << "->" << finish << '\n';
    unsigned char pow = lg[finish - start + 1];
    // std::cout << "Pow " << (unsigned short) pow << '\n';
    return std::min(
        dp[pow][finish - (1 << pow) + 1],
        dp[pow][start]
    );
}

int main()
{
    unsigned N, M;
    unsigned vec[SIZE];

    in >> N >> M;

    for(unsigned i = 0; i < N; i += 1) in >> vec[i];

    rmq_init(vec, N);

    unsigned a, b;
    for(unsigned i = 0; i < M; i += 1) {
        in >> a >> b;
        out << rmq_query(a - 1, b - 1) << '\n';
    }

    return 0;
}