#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ms(i, j) memset(i, j, sizeof i)
using namespace std;
const int MAXN = 50000 + 5;
int n, q;
int h[MAXN], fmaxi[MAXN][25], fmini[MAXN][25];
//h为原数组,fmaxi[i][j]为从i开始长度为2^j的区间最小值
void initRMQ() {
for (int i=1;i<=n;i++) fmaxi[i][0] = fmini[i][0] = h[i];//初始值为原数组
for (int j=1;(1<<j)<=n;j++) {//j必定在外层
for (int i=1;i+(1<<j)-1<=n;i++) {
fmaxi[i][j] = max(fmaxi[i][j-1], fmaxi[i+(1<<(j-1))][j-1]);
fmini[i][j] = min(fmini[i][j-1], fmini[i+(1<<(j-1))][j-1]);//DP
}
}
}
int RMQMax(int x, int y) {
int k = (int)(log(y-x+1.0)/log(2.0));
return max(fmaxi[x][k], fmaxi[y-(1<<k)+1][k]);
}
int RMQMin(int x, int y) {
int k = (int)(log(y-x+1.0)/log(2.0));
return min(fmini[x][k], fmini[y-(1<<k)+1][k]);
}
void clear() {}
void init() {
clear();
for (int i=1;i<=n;i++) scanf("%d", &h[i]);
initRMQ();
}
void solve() {
for (int i=1;i<=q;i++) {
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", RMQMax(a, b) - RMQMin(a, b));
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
#endif
while (scanf("%d%d", &n, &q)==2&&n&&q) init(), solve();
return 0;
}
poj 3264(ST表)
------ 本文结束 ------
版权声明
FlyInTheSky's blog by FlyInTheSky is licensed under a Creative Commons BY-NC-ND 4.0 International License.
由FlyInTheSky创作并维护的FlyInTheSky's blog博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证。
本文首发于FlyInTheSky's blog 博客( http://blog.flyinthesky.win/ ),版权所有,侵权必究。