http://poj.org/problem?id=3264
模板。
完整代码:
/*3891ms,1420KB*/ #include <cstdio> #include <algorithm> using namespace std; #define lson l, m, rt << 1 #define rson m + 1, r, rt << 1 | 1 #define root 1, n, 1 const int mx = 50000; int minh[mx << 2], maxh[mx << 2], x; inline void pushup(int rt) { maxh[rt] = max(maxh[rt << 1], maxh[rt << 1 | 1]); minh[rt] = min(minh[rt << 1], minh[rt << 1 | 1]); } void build(int l, int r, int rt) { if (l == r) { scanf("%d", &x); minh[rt] = maxh[rt] = x; return; } int m = (l + r) >> 1; build(lson); build(rson); pushup(rt); } int querymaxh(int ql, int qr, int l, int r, int rt) { if (ql <= l && r <= qr) { return maxh[rt]; } int maxh = 0, m = (l + r) >> 1; if (ql <= m) maxh = querymaxh(ql, qr, lson); if (m < qr) maxh = max(maxh, querymaxh(ql, qr, rson)); return maxh; } int queryminh(int ql, int qr, int l, int r, int rt) { if (ql <= l && r <= qr) { return minh[rt]; } int minh = 1000000, m = (l + r) >> 1; if (ql <= m) minh = queryminh(ql, qr, lson); if (m < qr) minh = min(minh, queryminh(ql, qr, rson)); return minh; } int main() { int n,m,a,b; scanf("%d%d", &n, &m); build(root); while (m--) { scanf("%d%d", &a, &b); printf("%d\n", querymaxh(a, b, root) - queryminh(a, b, root)); } return 0; }