ST表:利用二进制和动态规划的思想求解RMQ(区间最值)问题。
#include<iostream>
using namespace std;
const int N = 1e5 + 5;
int a[N], f[N][100]; // f[i][j] 从i开始2^j长度的区间
int n, m, _log[N];
void pre()
{
_log[0] = -1;
for (int i = 1; i <= N; i++) {
_log[i] = _log[i / 2] + 1;
}
}
void init()
{
for (int i = 1; i <= n; i++) {
f[i][0] = a[i];
}
int t = _log[n];
for (int j = 1; j <= t; j++)
{
for (int i = 1; i <= (n - (1 << j) + 1); i++)
{
f[i][j] = max(f[i][j - 1], f[i + (1 << (j - 1))][j - 1]);
}
}
}
int query(int l, int r)
{
int k = _log[r - l + 1];
return max(f[l][k], f[r - (1 << k) + 1][k]);
}
int main()
{
pre();
init();
cout << query(1, 8);
return 0;
}
|