Cod sursa(job #3204972)

Utilizator stefangab95Muscalu Stefan Gabriel stefangab95 Data 18 februarie 2024 14:15:28
Problema Range minimum query Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>

using namespace std;

// Preprocess the array to construct the Sparse Table
void build_sparse_table(const vector<int>& arr, int n, vector<vector<int>>& sparse_table) {
    int K = log2(n) + 1;
    
    // Initialize the table
    for (int i = 0; i < n; ++i)
        sparse_table[i][0] = arr[i];
    
    // Compute values from smaller to bigger intervals
    for (int j = 1; j <= K; ++j) {
        for (int i = 0; i + (1 << j) <= n; ++i) {
            sparse_table[i][j] = min(sparse_table[i][j-1], sparse_table[i + (1 << (j-1))][j-1]);
        }
    }
}

// Query the Sparse Table for the minimum value in range [L, R]
int query_sparse_table(int L, int R, const vector<vector<int>>& sparse_table) {
    int j = log2(R - L + 1);
    return min(sparse_table[L][j], sparse_table[R - (1 << j) + 1][j]);
}

int main() {
    ifstream fin("rmq.in");
    ofstream fout("rmq.out");
    
    int N, M;
    fin >> N >> M;
    vector<int> arr(N);
    for (int i = 0; i < N; ++i) {
        fin >> arr[i];
    }

    // Initialize Sparse Table
    int K = log2(N) + 1;
    vector<vector<int>> sparse_table(N, vector<int>(K + 1, 0));
    
    // Building the Sparse Table
    build_sparse_table(arr, N, sparse_table);
    
    // Answering the queries
    for (int i = 0; i < M; ++i) {
        int L, R;
        fin >> L >> R;
        fout << query_sparse_table(L - 1, R - 1, sparse_table) << endl;
    }

    fin.close();
    fout.close();
    
    return 0;
}