1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <cstdio> #include <algorithm> using namespace std; int n, m, h, l, r; const int N = 500001, INF = 0x3f3f3f3f; struct Node { int l, r, min_val, max_val; } tr[N << 2]; void build(int u, int l, int r) { tr[u] = {l, r, 0, 0}; if (l == r) { scanf("%d", &h), tr[u].min_val = tr[u].max_val = h; } else { int mid = (l + r) >> 1; build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r); tr[u].min_val = min(tr[u << 1].min_val, tr[u << 1 | 1].min_val); tr[u].max_val = max(tr[u << 1].max_val, tr[u << 1 | 1].max_val); } } int find_max(int u, int l, int r) { if (l <= tr[u].l && tr[u].r <= r) return tr[u].max_val; int mid = (tr[u].l + tr[u].r) >> 1, ans = -INF; if (l <= mid) ans = find_max(u << 1, l, r); if (r > mid) ans = max(ans, find_max(u << 1 | 1, l, r)); return ans; } int find_min(int u, int l, int r) { if (l <= tr[u].l && tr[u].r <= r) return tr[u].min_val; int mid = (tr[u].l + tr[u].r) >> 1, ans = INF; if (l <= mid) ans = find_min(u << 1, l, r); if (r > mid) ans = min(ans, find_min(u << 1 | 1, l, r)); return ans; } int main() { scanf("%d%d", &n, &m); build(1, 1, n); while (m--) { scanf("%d%d", &l, &r); printf("%d\n", find_max(1, l, r) - find_min(1, l, r)); } return 0; }
|