You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.3 KiB

2 years ago
#include <algorithm>
#include <cstdio>
#include <cstring>
const int INF = 0x3f3f3f3f;
using namespace std;
const int N = 50010;
int a[N];
int n, q;
// 树状数组模板
int c1[N], c2[N]; // c1:维护最大值c2维护最小值
int lowbit(int x) {
return x & -x;
}
void update(int x, int d) {
for (int i = x; i < N; i += lowbit(i)) c1[i] = max(c1[i], d), c2[i] = min(c2[i], d);
}
int query(int x, int y) {
int mx = 0, mi = INF;
while (y >= x) { // 右侧到左侧
mx = max(mx, a[y]), mi = min(mi, a[y]); // 每次最后侧的点参加评比
for (--y; y - x >= lowbit(y); y -= lowbit(y)) // 从x~y-1检查每个片断
mx = max(mx, c1[y]), mi = min(mi, c2[y]);
}
return mx - mi;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("POJ3264.in", "r", stdin);
#endif
memset(c1, 0, sizeof c1);
memset(c2, 0x3f, sizeof c2); // 最小值需要先设置最大最大值默认的就是0不需要设置
scanf("%d %d", &n, &q);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
update(i, a[i]);
}
while (q--) {
int a, b;
scanf("%d %d", &a, &b);
printf("%d\n", query(a, b));
}
return 0;
}