sparse table

Правка en1, от bobby6264, 2025-09-29 16:35:12

Sparse table. A master algorithm that use to solve the query on an immutable array for the operations like idempotent.

Immutable: the content of the array does not change with time or with queries, if so , then you should use other data structures like segment tree or you have to re calculate every time.

idempotent: operations like Minimum, Maximum, GCD, LCM, Bitwise AND, Bitwise OR.

here look the code, i have tried to write below for calculating the minimum of the ranges from index l to index r.

#include<bits/stdc++.h>
using namespace std;

using lli = long long;
#define endl "\n"

#define MAXN 200005
#define K 25 

vector<vector<int>>st(MAXN,vector<int>(K));
int log_table[MAXN];

void precompute_logs(int n) {
    log_table[1] = 0;
    for (int i = 2; i <= n; i++) {
        log_table[i] = log_table[i / 2] + 1;
    }
}

// trying to build a sparse table that keep minimum of a range
void buildTable(vector<int> & arr){
    int n = arr.size();
    st.resize(n,vector<int>(25,1e9));
    for(int i =0; i<n;i++){
        st[i][0]=arr[i];
    }
    for(int i =1; i<K ;i++){
        for(int j =0; j + (1 << i) <= n;j++){
            st[j][i] = min(st[j][i-1],st[j+(1<<(i-1))][i-1]);
        }
    }
    
}

int query(int l , int r){
    int len = r-l +1;
    int lg = log_table[len];
    return min(st[l][lg],st[r-(1<<lg)+1][lg]);
}

void solve(){
    vector<int> arr={1,2,3,4,23,4,54,3,2,8};
    int n = arr.size();
    precompute_logs(n);
    buildTable(arr);
    cout<<query(0,5)<<endl<<query(4,4);
}

signed main(){
    int t = 1;
    cin>>t;
    while(t--){
        solve();
    }
}
  1. precompute_logs(int n) The core idea of querying is to split a range [l, r] of length len into two overlapping subproblems of size 2^k, where k is the largest integer such that 2^k <= len. This k is simply floor(log2(len)).

  2. buildTable(const vector& arr) This is the heart of the algorithm—the O(N log N) precomputation. We'll use a 2D array, st[i][j], to store the minimum of the range starting at index i with length 2^j.

  3. query(int l, int r) This is where we reap the rewards! Answering a query for [l, r] is now an O(1) operation.

Calculate the length of the range.

Find the largest power of two (k) that fits within this length using our log_table.

Find the minimum of two ranges of length 2^k: one starting at l and another one ending at r. Because min is idempotent, their overlap doesn't affect the result.

Теги range query, sparse table, range minimum query, rmq

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский bobby6264 2025-09-29 16:35:12 2549 Initial revision (published)