ST表,求区间内的最大最小值。预处理 时间复杂度为O(nlogn),查询时间O(1)。视频详解
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int f[N][18]; // 2^17 = 131072 > 100000
int n, m;
int query(int l, int r) {
int d = log2(r-l+1);
return max(f[l][d], f[r-(1<<d)+1][d]);
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> f[i][0];
}
//预处理
int width = log2(n) + 1;
for (int j = 1; j <= width; j++) {
// 不能越界: i + (1 << j) - 1 <= n (从表示的意义出发)
for (int i = 1; i + (1 << j) - 1 <= n; i++) {
f[i][j] = max(f[i][j-1], f[i + (1 << (j-1))][j-1]);
}
}
int l, r;
for (int i = 1; i <= m; i++) {
cin >> l >> r;
cout << query(l, r) << endl;
}
return 0;
}