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 should 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
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0 #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int MAXN = 50500; int hei[MAXN]; struct Tree { int l, r, ma, mi; } tree_a[MAXN*4], tree_i[MAXN*4]; void bulid_ma(int root, int l, int r) { tree_a[root].l = l; tree_a[root].r = r; if(tree_a[root].r == tree_a[root].l) { tree_a[root].ma = hei[l]; return; } int mid = (l+r)/2; bulid_ma(root<<1, l, mid); bulid_ma(root<<1|1, mid+1, r); tree_a[root].ma = max(tree_a[root<<1].ma, tree_a[root<<1|1].ma); } void bulid_mi(int root, int l, int r) { tree_i[root].l = l; tree_i[root].r = r; if(tree_i[root].r == tree_i[root].l) { tree_i[root].mi = hei[l]; return; } int mid = (l+r)/2; bulid_mi(root<<1, l, mid); bulid_mi(root<<1|1, mid+1, r); tree_i[root].mi = min(tree_i[root<<1].mi, tree_i[root<<1|1].mi); } int query(int root, int l, int r, char f) { if( 'a' == f ) { if(l<=tree_a[root].l && r>=tree_a[root].r) { return tree_a[root].ma; } int mid = (tree_a[root].l+tree_a[root].r)/2, ret = 0; if(l<=mid) ret = max(ret,query(root<<1, l, r, f)); if(r>mid) ret = max(ret,query(root<<1|1,l, r, f)); return ret; } else if( 'i' == f ) { if(l<=tree_i[root].l && r>=tree_i[root].r) { return tree_i[root].mi; } int mid = (tree_i[root].l+tree_i[root].r)/2, ans = 100000000; if(l<=mid) ans = min(ans,query(root<<1, l, r, f)); if(r>mid) ans = min(ans,query(root<<1|1, l, r, f)); return ans; } } int main() { int n, q; scanf("%d%d", &n, &q); memset(hei, 0, sizeof(hei)); memset(tree_a, 0, sizeof(tree_a)); memset(tree_i, 0, sizeof(tree_i)); for(int i=1; i<=n; i++ ) { scanf("%d", &hei[i]); } bulid_ma(1, 1, n); bulid_mi(1, 1, n); int r, l; for(int i=0; i<q; i++ ) { scanf("%d%d", &l, &r); printf("%d\n", query(1, l, r, 'a') - query(1, l, r, 'i')); } return 0; } 哎, 我就是个马大哈。。。