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
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.
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
初看此题,可能会想到用最简单的暴力。可是结局很明显会被TLE。其实它是典型的线段树的例子,在完全二叉树中,总结点数不会超过叶子节点的两倍。
请看代码如下
1 #include <iostream> 2 #include <cmath> 3 #include <cstdio> 4 #include <cstdlib> 5 #include <cstring> 6 #include <string> 7 #include <algorithm> 8 using namespace std; 9 10 int const N=50010; 11 int a[N]; 12 13 struct node 14 { 15 int l,r; 16 int low,high; 17 }; 18 19 node tree[3*N]; 20 21 int hei,low; 22 23 void build(int l,int r,int p) 24 { 25 tree[p].l=l; 26 tree[p].r=r; 27 if(l==r) 28 { 29 tree[p].low=a[l]; 30 tree[p].high=a[l]; 31 return; 32 } 33 int mid=(l+r)/2; 34 build(l,mid,2*p); 35 build(mid+1,r,2*p+1); 36 tree[p].low=min(tree[2*p].low,tree[2*p+1].low); 37 tree[p].high=max(tree[2*p].high,tree[2*p+1].high); 38 } 39 40 void ask(int l,int r,int p) 41 { 42 if(tree[p].l==l&&tree[p].r==r) 43 { 44 low=min(low,tree[p].low); 45 hei=max(hei,tree[p].high); 46 return ; 47 } 48 int mid=(tree[p].l+tree[p].r)/2; 49 if(r<=mid) ask(l,r,2*p); 50 else if(l>=mid+1) ask(l,r,2*p+1); 51 else 52 { 53 ask(l,mid,2*p); 54 ask(mid+1,r,2*p+1); 55 } 56 } 57 58 int main() 59 { 60 int m,n; 61 while(~scanf("%d%d",&m,&n)) 62 { 63 for(int i=1;i<=m;i++) 64 scanf("%d",&a[i]); 65 build(1,m,1); 66 for(int i=1;i<=n;i++) 67 { 68 int x,y; 69 scanf("%d%d",&x,&y); 70 low=1000001; 71 hei=0; 72 ask(x,y,1); 73 printf("%d\n",hei-low); 74 } 75 } 76 return 0; 77 }