ProgramAlgTrain/20240919/CSP常考算法模板/RMQ.cpp

40 lines
839 B
C++
Raw Normal View History

2024-09-19 02:22:41 +00:00
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
const int LOGN = 20;
2024-09-19 03:11:59 +00:00
int Log[N] = {-1}, f[N][LOGN + 1], a[N]; // f[i][j] 存储[i, i+2^j-1]之间的最值
2024-09-19 02:22:41 +00:00
int n, m;
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>n>>m;
for(int i=1; i<=n; ++i) {
cin>>a[i];
}
for(int i=1; i<=n; ++i) {
f[i][0]=a[i];
2024-09-19 03:11:59 +00:00
Log[i]=Log[i>>1] + 1; // 预处理出长度为1~n的log值
2024-09-19 02:22:41 +00:00
}
2024-09-19 03:11:59 +00:00
for(int j=1; j<=LOGN; j++) { // 注意是j
for(int i=1; i+(1<<j)-1<=n; i++) { // 注意要加括号(1<<j)
2024-09-19 02:22:41 +00:00
f[i][j]=max(f[i][j-1], f[i+(1<<(j-1))][j-1]);
}
}
for (int i = 1; i <= m; i++) {
int x, y;
cin>>x>>y;//3 8
int s=Log[y-x+1];
cout<<max(f[x][s], f[y-(1<<s)+1][s])<<endl;
}
return 0;
}