description
查询区间最大和最小
题解
线段树
愉悦身心啊
代码
![](http://img.e-com-net.com/image/info8/b8d97b5613f94ed2ba791cad57d0b2ed.gif)
![](http://img.e-com-net.com/image/info8/2f88dd3f1cd145f59c0e47b51acdbd4b.gif)
1 #include2 #include 3 #include 4 #define rd read() 5 #define lson nd << 1 6 #define rson nd << 1 | 1 7 using namespace std; 8 9 const int N = 1e5; 10 const int inf = ~0U >> 1; 11 12 int MAX[N << 2], MIN[N << 2], a[N], q, n; 13 14 int read() { 15 int X = 0, p = 1; char c = getchar(); 16 for(; c > '9' || c < '0'; c = getchar()) if(c == '-') p = -1; 17 for(; c >= '0' && c <= '9';c = getchar()) X = X * 10 + c - '0'; 18 return X * p; 19 } 20 21 void print(int x) { 22 if(x < 0) putchar('-'), x = -x; 23 if(x >= 10) print(x / 10); 24 putchar(x % 10 + '0'); 25 } 26 27 void update(int nd) { 28 MIN[nd] = min(MIN[lson], MIN[rson]); 29 MAX[nd] = max(MAX[lson], MAX[rson]); 30 } 31 32 void build(int l, int r, int nd) { 33 if(l == r) { 34 MIN[nd] = MAX[nd] = a[l]; 35 return; 36 } 37 int mid = (l + r) >> 1; 38 build(l, mid, lson); 39 build(mid + 1, r, rson); 40 update(nd); 41 } 42 43 int query_max(int L, int R, int l, int r, int nd) { 44 if(L <= l && r <= R) return MAX[nd]; 45 int mid = (l + r) >> 1, tmp = 0; 46 if(L <= mid) tmp = max(tmp, query_max(L, R, l, mid, lson)); 47 if(mid < R) tmp = max(tmp, query_max(L, R, mid + 1, r, rson)); 48 return tmp; 49 } 50 51 int query_min(int L, int R, int l, int r, int nd) { 52 if(L <= l && r <= R) return MIN[nd]; 53 int mid = (l + r) >> 1, tmp = inf; 54 if(L <= mid) tmp = min(tmp, query_min(L, R, l, mid, lson)); 55 if(mid < R) tmp = min(tmp, query_min(L, R, mid + 1, r, rson)); 56 return tmp; 57 } 58 59 int main() 60 { 61 n = rd; q = rd; 62 for(int i = 1; i <= n; ++i) a[i] = rd; 63 build(1, n, 1); 64 for(int i = 1; i <= q; ++i) { 65 int l = rd, r = rd; 66 int mx = query_max(l, r, 1, n, 1), mn = query_min(l, r, 1, n, 1); 67 print(mx - mn); 68 putchar('\n'); 69 } 70 }