题目大意:给你N个数,然后询问,询问的是区间内最大值和最小值的差
解题思路:线段树的裸题了,维护最大值和最小值即可
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 50010 << 2;
int n, q;
int val[N], Min[N], Max[N];
void PushUp(int u) {
Max[u] = max(Max[u << 1], Max[u << 1 | 1]);
Min[u] = min(Min[u << 1], Min[u << 1 | 1]);
}
void build(int u, int l, int r) {
if (l == r) {
Max[u] = Min[u] = val[l];
return ;
}
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
PushUp(u);
}
int query(int u, int l, int r, int L, int R, int flag) {
if (L <= l && r <= R) {
if (flag) return Max[u];
else return Min[u];
}
int mid = (l + r) >> 1;
int ans = INF;
if (flag) ans = -INF;
if (L <= mid) {
if (flag) ans = max(ans, query(u << 1, l, mid, L, R, flag));
else ans = min(ans, query(u << 1, l, mid, L, R, flag));
}
if (R > mid) {
if (flag) ans = max(ans, query(u << 1 | 1, mid + 1, r, L, R, flag));
else ans = min(ans, query(u << 1 | 1, mid + 1, r, L, R, flag));
}
return ans;
}
void solve() {
for (int i = 1; i <= n; i++)
scanf("%d", &val[i]);
build(1, 1, n);
int a, b;
while (q--) {
scanf("%d%d", &a, &b);
printf("%d\n", query(1, 1, n, a, b, 1) - query(1, 1, n, a, b, 0));
}
}
int main() {
while (scanf("%d%d", &n, &q) != EOF) solve();
return 0;
}