# Include <iostream> # include <cstdio> # include <cstring> # include <vector> # include <algorithm> # include <cstdlib> // Accepted4868K3016MSC ++ 2390B2013-08-09 12:45:26/second ++ 2390B2013-08-09 12: 44: 44 using namespace std; const int maxn = 50100; const int INF = 0x7fffff; struct Node {int Left, Right; int maxval, minxval; Node * LeftChild, * RightChild; node () {maxval =-1; // ensure that the update will not go wrong during insertion. Minxval = INF ;}}; int ql, qr; // global variable, that is, each insert or query interval. Int Min, Max; // Save the maximum value of the interval to be queried. int n, m; Node * root = NULL; void Build (Node * cur, int L, int R) {cur-> Left = L; cur-> Right = R; if (L! = R) {cur-> LeftChild = new Node; cur-> RightChild = new Node; Build (cur-> LeftChild, L, (L + R)/2 ); build (cur-> RightChild, (L + R)/2 + 1, R);} else {// L = R cur-> LeftChild = NULL; // No children left or right. Cur-> RightChild = NULL ;}// assign a value to ql each time you insert a value. void update (Node * cur, int L, int R, int value) {if (L = R & L = ql) {// leaf Node. Cur-> maxval = value; cur-> minxval = value; return;} Node * LC = cur-> LeftChild; Node * RC = cur-> RightChild; int M = (L + R)/2; if (ql <= M) update (LC, L, M, value); else update (RC, M + 1, R, value); cur-> maxval = max (LC-> maxval, RC-> maxval); cur-> minxval = min (LC-> minxval, RC-> minxval );} // interval: [ql, qr], Min, and Max global variables are initialized. Void query (Node * cur, int L, int R) {if (ql <= L & R <= qr) {Min = min (Min, cur-> minxval ); max = max (Max, cur-> maxval); return;} Node * LC = cur-> LeftChild; Node * RC = cur-> RightChild; int M = (L + R)/2; if (ql <= M) query (LC, L, M); if (qr> M) query (RC, M + 1, R); return;} void init () {int tmp; Max =-1; // littl, import; Min = 10000000; // big Build (root, 1, n); for (int I = 1; I <= n; I ++) {scanf ("% d ", & Tmp); ql = I; update (root, 1, n, tmp) ;}} int main () {int start, endx; while (scanf ("% d", & n, & m )! = EOF) {root = new Node; init (); for (int I = 1; I <= m; I ++) {scanf ("% d ", & start, & endx); ql = start, qr = endx; Max =-1, Min = INF; query (root, 1, n); int res = Max-Min; printf ("% d \ n", res) ;}} return 0 ;}