Description
For the daily milking, Farmer John's N cows (1 ≤ N ≤50,000) always line up in the same order. one day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. to keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. however, for all the cows to have fun they shocould not differ too much in height.
Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000 ). for each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.
Input
Line 1: Two space-separated integers, N and Q.
Lines 2. N + 1: Line I + 1 contains a single integer that is the height of cow I
Lines N + 2. N + Q + 1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.
Output
Lines 1. Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2 Sample Output
6
3
0
# Include <iostream> # include <cstdlib> # include <cstdio> # include <cstring> # include <climits> using namespace std;/* int max (int a, int B) {return a> B? A: B;} */const int MAXN = 50010; struct tnode {int l, r, mmax, mmin;}; tnode node [MAXN * 4]; int a [MAXN], maxv, minv; void init (int k, int l, int r) // The interval corresponding to node k is [l, r) {node [k]. l = l; node [k]. r = r; if (r-l = 1) {// if the interval has only one element, node [k]. mmax = node [k]. mmin = a [l]; return;} int mid = (l + r)/2; init (2 * k + 1, l, mid ); init (2 * k + 2, mid, r); // construct left and right subtree node [k] respectively. mmax = max (node [2 * k + 1]. mmax, node [2 * k + 2]. mmax); node [k]. mmin = min (node [2 * k + 1]. mmin, node [2 * k + 2]. mmin);} void query (int l, int r, int k) {if (node [k]. l = l & node [k]. r = r) {// the query interval and node interval completely coincide with maxv = max (maxv, node [k]. mmax); minv = min (minv, node [k]. mmin); return;} int mid = (node [k]. l + node [k]. r)/2; if (mid <= l) query (l, r, 2 * k + 2 ); // The queried range is in the right subtree else if (mid> = r) query (l, r, 2 * k + 1 ); // The queried range is in the left subtree else {query (l, mid, 2 * k + 1); // The queried range is in the left subtree query (mid, r, 2 * k + 2) ;}} int main () {int n, q; while (cin >>n> q) {memset (node, 0, sizeof (node); for (int I = 0; I <n; I ++) scanf ("% d", & a [I]); init (0, 0, n); // initialize the line segment tree for (int I = 0; I <q; I ++) {int x, y; scanf ("% d ", & x, & y); maxv = 0; minv = INT_MAX; query (x-1, y, 0 ); // here is the left closed right open range cout <maxv-minv <endl ;}} return 0 ;}