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<cstdlib> #include<string> #include<algorithm> #include<cstdio> #include<cmath> #include<cstring> #include<stack> #include<queue> #include<iomanip> #include<map> #define pi 3.14159265358979323846 using namespace std; struct node { int big; int small; }; node tree[200001]; /*void build(int p,int l,int r) { if(l==r) {tree[p].big=height[l];tree[p].small=height[l];return;} int mid=(l+r)/2; build(p*2,l,mid); build(p*2+1,mid+1,r); return ; }*/ void change(int p,int l,int r,int x,int num) { if(l==r) {tree[p].small+=num;tree[p].big+=num;return;} int mid=(l+r)/2; if(x<=mid) change(p*2,l,mid,x,num); else change(p*2+1,mid+1,r,x,num); tree[p].small=min(tree[p*2].small,tree[p*2+1].small); tree[p].big=max(tree[p*2].big,tree[p*2+1].big); } int find_max(int p,int l,int r,int x,int y) { if(x<=l&&r<=y) return tree[p].big; int mid=(l+r)/2; if(y<=mid) return find_max(p*2,l,mid,x,y); if(x>mid) return find_max(p*2+1,mid+1,r,x,y); return max(find_max(p*2,l,mid,x,mid),find_max(p*2+1,mid+1,r,mid+1,y)); } int find_min(int p,int l,int r,int x,int y) { if(x<=l&&r<=y) return tree[p].small; int mid=(l+r)/2; if(y<=mid) return find_min(p*2,l,mid,x,y); if(x>mid) return find_min(p*2+1,mid+1,r,x,y); return min(find_min(p*2,l,mid,x,mid),find_min(p*2+1,mid+1,r,mid+1,y)); } int main() { int N,Q; scanf("%d %d",&N,&Q); int height; for(int i=1;i<=N;++i) { scanf("%d",&height); change(1,1,50000,i,height); } int x,y; int smax,smin; for(int i=0;i<Q;++i) { scanf("%d %d",&x,&y); smax=find_max(1,1,50000,x,y); smin=find_min(1,1,50000,x,y); printf("%d\n",smax-smin); } return 0; }