Cod sursa(job #2922855)

Utilizator TheRomulusIvan Remus TheRomulus Data 10 septembrie 2022 13:13:12
Problema Range minimum query Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>

#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <deque>
#include <queue>
#include <stack>

using namespace std;

ifstream fin("rmq.in");
ofstream fout("rmq.out");

typedef long long ll;

/**
 * @brief computes a sparse table(i think that's the name :P ) for a given vector
 * the counting is done from 0 to n-1
 * table[i][j]=the min of the sequence that start at position j and takes the next 2^i elements,including j
 * @param elements the initial elements
 * @return vector<vector<ll>> the sparse table
 */
vector<vector<ll>> computeSparseTable(vector<ll>& elements) {
    int n = elements.size();
    vector<vector<ll>> table;
    table.assign(log2(n) + 1, vector<ll>(n, 0));

    table[0] = elements;

    for (int l = 1, i = 1; i <= log2(n); ++i, l = l << 1) {
        for (int j = 0; j < n - (2 * l - 1); ++j) {
            table[i][j] = min(table[i - 1][j], table[i - 1][j + l]);
        }
    }

    // for(int l=1,i=1;i<=log2(n);++i,l=l<<1){
    //     for(int j=0;j<n-(2*l-1);++j){
    //         fout<<table[i][j]<<' ';
    //     }
    //     fout<<'\n';
    // }

    return table;
}

//Computes the query in log(length) time using the sparse table
ll computeQuery(vector<vector<ll>>& table, int start, int length) {
    ll value = 1e9;
    for (int i = log2(table[0].size()); i >= 0; --i) {
        int p = 1 << i;
        if (p <= length) {
            value = min(value, table[i][start]);
            length -= p;
            start += p;
        }
    }
    return value;
}

void Solve() {
    int n,q;
    fin >> n >> q;
    vector<ll> v(n);
    for (int i = 0; i < n; ++i) {
        fin >> v[i];
    }

    auto table = computeSparseTable(v);

    for (int i = 0; i < q; ++i) {
        int x, y;
        fin >> x >> y;
        fout << computeQuery(table, x - 1, y - x + 1) << '\n';
    }
}

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    Solve();

    return 0;
}