2026/7/13下午 区间倍增总结

· · 个人记录

P3865 【模板】ST 表 & RMQ 问题

题面

时间复杂度:O(n log n)

转换方式:st[i][j]=max(st[i][j-1],st[i+(1<<(j-1))][j-1]);

ST表是一种专门解决静态区间最值查询(RMQ) 问题的数据结构。

它的核心是利用倍增思想和DP递推:预先计算并存储所有以任意位置为起点、长度为 (2^j) 的区间最值(即 (st[i][j])),转移方程是 (st[i][j] = max(st[i][j-1], st[i+2^{j-1}][j-1])),预处理时间复杂度为 (O(n\log n))。

在查询任意区间 ([l, r]) 时,只需计算出区间长度的最高位 (k = \lfloor \log_2(r-l+1) \rfloor),然后将该区间“重叠”地拆分成两个长度为 (2^k) 的已预处理区间,直接取最大值即可,单次查询时间复杂度仅为 (O(1))。

#include<bits/stdc++.h>
#define int long long
#define f first
#define s second
using namespace std;
const int N=1e6+50;
int n,m,ans,a[N],st[N][22],lg[N];
int query(int l,int r){
    int k=lg[r-l+1];
    return max(st[l][k],st[r-(1<<k)+1][k]);
}
void init(){
    lg[1]=0;
    for(int i=2;i<=n;i++){
        lg[i]=lg[i/2]+1;
    }
    for(int j=1;j<=20;j++){
        for(int i=1;i+(1<<(j-1))-1<=n;i++){
            st[i][j]=max(st[i][j-1],st[i+(1<<(j-1))][j-1]);
        }
    }
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        st[i][0]=a[i];
    }
    init();
    while (m--){
        int l,r;
        cin>>l>>r;
        cout<<query(l,r)<<"\n";
    }
    return 0;
}

P1890 gcd 区间

题面

把选最大值的部分改为取最大公因数

#include<bits/stdc++.h>
#define int long long
#define f first
#define s second
using namespace std;
const int N=1e6+50;
int n,m,ans,a[N],st[N][22],lg[N];
int query(int l,int r){
    int k=lg[r-l+1];
    return __gcd(st[l][k],st[r-(1<<k)+1][k]);
}
void init(){
    lg[1]=0;
    for(int i=2;i<=n;i++){
        lg[i]=lg[i/2]+1;
    }
    for(int j=1;j<=20;j++){
        for(int i=1;i+(1<<(j-1))-1<=n;i++){
            st[i][j]=__gcd(st[i][j-1],st[i+(1<<(j-1))][j-1]);
        }
    }
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        st[i][0]=a[i];
    }
    init();
    while (m--){
        int l,r;
        cin>>l>>r;
        cout<<query(l,r)<<"\n";
    }
    return 0;
}

P1198 [JSOI2008] 最大数

题面

代码的核心是维护一个逆向(或动态)ST 表。