题面:给定数组A[n],有Q次查询,每次询问区间[l,r]的最大值。
范围:2 <= n <= 1E4, 0 <= A[i] <= 1E9, 2 <= Q <= 1E4, 0 <= l <= r < n
思路:如果有修改,可以考虑线段树,这里只有静态查询,可以用ST表,预处理时间O(nlogn),单次查询时间O(1)。
#include <bits/stdc++.h>
const int N = 100005;
int Max[N][21];
int qmax(int l, int r) {
int k = std::__lg(r-l);
return std::max(Max[l][k], Max[r-(1<<k)][k]);
}
void solve() {
int n;
std::cin >> n;
for (int i = 1; i <= n; i++) {
std::cin >> Max[i][0];
}
for (int j = 1; j <= 20; j++) {
for (int i = 1; i + (1 << j) <= n + 1; i++) {
Max[i][j] = std::max(Max[i][j-1], Max[i+(1<<(j-1))][j-1]);
}
}
int Q;
std::cin >> Q;
while (Q--) {
int x, y;
std::cin >> x >> y;
x++, y++;
std::cout << qmax(x, y+1) << "\n";
}
}
int main() {
std::cin.tie(0)->sync_with_stdio(0);
int t = 1;
while (t--) solve();
return 0;
}
标签:倍增