[模板]ST表

题目←

可以O(1)的解决RMQ问题
不过不支持修改
基本基于DP,以最大值为例,st[i][j] = max(st[i][j - 1],st[i + (1 << j - 1)][j - 1]);

#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN = 200000 + 50;
int st[MAXN][30],n,m,l,ln[MAXN];
void init(int n){
    for(int i = 1;i <= n;i ++){
        scanf("%d",&st[i][0]);
    }
    for(int i = 1;i <= n;i ++){
        ln[i] = (1 << l + 1 == i) ? ++ l : l;
    }
    for(int j = 1;(1 << j) <= n + 1;j ++){
        for(int i = 1;i + (1 << j) <= n + 1;i ++){//初始化到n + 1
            st[i][j] = max(st[i][j - 1],st[i + (1 << j - 1)][j - 1]);
        }
    }
}
int x,y;
int main(){
    scanf("%d%d",&n,&m);
    init(n);
    for(int i = 1;i <= m;i ++){
        scanf("%d%d",&x,&y);
        int k = ln[y - x + 1];
        printf("%d\n",max(st[x][k],st[y - (1 << k) + 1][k]));
    }
}
### ST简介 ST(Sparse Table)是一种用于解决静态区间的最值查询问题的数据结构。其预处理时间为 \(O(n \log n)\),每次查询的时间复杂度为 \(O(1)\)[^1]。 ### ST模板代码 以下是C++实现的ST模板代码: ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; const int MAXN = 1e5 + 5; int st[MAXN][20]; // Sparse table to store the minimum value in intervals of length 2^j starting from i. int log_table[MAXN]; // Precomputed logarithms. void preprocess(int arr[], int n) { // Precompute log values for efficient computation during sparse table construction. log_table[1] = 0; for (int i = 2; i <= n; ++i) { log_table[i] = log_table[i >> 1] + 1; } // Initialize first column with input array elements. for (int i = 0; i < n; ++i) { st[i][0] = arr[i]; } // Fill up the sparse table using dynamic programming approach. for (int j = 1; (1 << j) <= n; ++j) { // For each power of two interval size for (int i = 0; i + (1 << j) - 1 < n; ++i) { // Ensure that we do not go out of bounds while filling entries st[i][j] = min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]); } } } // Query function returns the minimum element within range [L,R]. int query_min(int L, int R) { int k = log_table[R - L + 1]; return min(st[L][k], st[R - (1 << k) + 1][k]); } ``` 此段代码实现了构建和查询功能,可以应用于多种场景下的区间最值查询问题。 ### 应用实例 假设有一个整数数组 `arr` 和若干次询问 `[l, r]` 来获取该范围内最小值,则可以通过上述方法快速得到结果而无需每次都遍历整个范围来查找最小值。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值