st表
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int N = 2e5 + 10, M = 18;
int f[N][M], a[N];
int n, m;
void init()
{
for (int j = 0; j < M; j++)
for (int i = 1; i + (1 << j) - 1 <= n; i++)
if (!j)
f[i][j] = a[i];
else
f[i][j] = max(f[i][j-1], f[i + (1 << j-1)][j-1]);
}
int query(int l, int r)
{
int len = r - l + 1;
int k = log(len) / log(2);
return max(f[l][k], f[r - (1<<k) + 1][k]);
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
init();
cin >> m;
while(m--)
{
int l, r;
cin >> l >> r;
cout << query(l, r) << endl;
}
return 0;
}
类模板
template<typename T> struct ST
{
ST(T a[], int n){
siz = n;
maxv.resize(n+1); minv.resize(n+1);
int t = __lg(n) + 1;
for(int i=1;i<=n;i++) maxv[i].resize(t), minv[i].resize(t);
for(int i = 1; i <= n; i++) maxv[i][0] = minv[i][0] = a[i];
for(int j = 1; j < t; j++)
{
for(int i = 1; i <= n - (1<<j)+1; i++)
{
maxv[i][j] = max(maxv[i][j-1], maxv[i+(1 << (j-1))][j-1]);
minv[i][j] = min(minv[i][j-1], minv[i+(1 << (j-1))][j-1]);
}
}
}
T getmax(int l,int r)
{
int k = __lg(r-l+1);
return max(maxv[l][k],maxv[r-(1<<k)+1][k]);
}
T getmin(int l,int r)
{
int k = __lg(r-l+1);
return min(minv[l][k],minv[r-(1<<k)+1][k]);
}
private:
int siz = 0;
vector<vector<T>> maxv, minv;
};