#include <bits/stdc++.h>
using namespace std;
const int maxn = 50010;
int n, h[maxn], q, l, r, log_2[maxn], rmax[maxn][18], rmin[maxn][18];
void init() {
for (int i = 1; i <= n; i++) rmax[i][0] = rmin[i][0] = h[i];
for (int j = 1; (1 << j) <= n; j++)
for (int i = 1; i <= n - (1 << j) + 1; i++) {
rmax[i][j] = max(rmax[i][j - 1], rmax[i + (1 << j - 1)][j - 1]);
rmin[i][j] = min(rmin[i][j - 1], rmin[i + (1 << j - 1)][j - 1]);
}
}
int mymax(int l, int r) {
int x = log_2[r - l + 1];
return max(rmax[l][x], rmax[r - (1 << x) + 1][x]);
}
int mymin(int l, int r) {
int x = log_2[r - l + 1];
return min(rmin[l][x], rmin[r - (1 << x) + 1][x]);
}
int main() {
cin >> n >> q;
for (int i = 1; i <= n; i++) cin >> h[i];
for (int i = 2; i <= n; i++) log_2[i] = log_2[i >> 1] + 1;
init();
while (q--) {
cin >> l >> r;
cout << mymax(l, r) - mymin(l, r) << endl;
}
return 0;
}
你不是过了吗? |