给出一个有n个数的序列,下标0~n-1
,有Q次查询,每次询问区间[l,r]的最大值。
如果有修改,可以考虑线段树,这里只有静态查询,可以用ST表,预处理时间O(nlogn),单次查询时间O(1)。
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=b;i>=a;i--)
const int N = 100005;
int n, Q, a[N], Min[N][21], Max[N][21];
int qmin(int l, int r) {
int k = log2(r-l);
return min(Min[l][k], Min[r-(1<<k)][k]);
}
int qmax(int l, int r) {
int k = log2(r-l);
return max(Max[l][k], Max[r-(1<<k)][k]);
}
void solve() {
cin >> n;
rep(i,1,n) cin >> a[i];
rep(i,1,n) Min[i][0] = Max[i][0] = a[i];
rep(j,1,20) {
for (int i = 1; i+(1<<j) <= n+1; i++) {
Min[i][j] = min(Min[i][j-1], Min[i+(1<<(j-1))][j-1]);
Max[i][j] = max(Max[i][j-1], Max[i+(1<<(j-1))][j-1]);
}
}
cin >> Q;
while (Q--) {
int x, y;
cin >> x >> y;
x++, y++;
cout << qmax(x, y+1) << "\n";
}
}
signed main() {
cin.tie(0)->sync_with_stdio(0);
int t = 1;
while (t--) solve();
return 0;
}
标签:RMQ,Min,int,rep,查询,--,51nod1174,区间
From: https://www.cnblogs.com/chenfy27/p/18084138