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
Source
#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int N,Q,cows[50001],A,B; int cal(int a,int b){ int max=cows[a],min=cows[a]; for(int i=a+1;i<=b;i++){ if(max<cows[i]) max=cows[i]; if(min>cows[i]) min=cows[i]; } return max-min; } struct node{ int l,r,min,max; }tree[50001*3]; struct maxmin{ int max,min; }; void build(int k,int l,int r){ tree[k].l=l; tree[k].r=r; if( l==r ){ tree[k].max=max(cows[l],cows[r]); tree[k].min=min(cows[l],cows[r]); } else{ build(2*k+1,l,(l+r)/2); build(2*k+2,(l+r)/2+1,r); tree[k].max=max(tree[2*k+1].max,tree[2*k+2].max); tree[k].min=min(tree[2*k+1].min,tree[2*k+2].min); } } int query(int k,int l,int r,int *Max,int *Min){ int max1,max2,min1,min2; if(tree[k].l==l && tree[k].r==r){ (*Max)=tree[k].max; (*Min)=tree[k].min; return (*Max)-(*Min); } int mid=(tree[k].l+tree[k].r)/2; if( r<=mid ){ query(2*k+1,l,r,Max,Min); return (*Max)-(*Min); } else if( l>=mid+1 ){ query(2*k+2,l,r,Max,Min); return (*Max)-(*Min); } else{ query(2*k+1,l,mid,Max,Min); max1=(*Max); min1=(*Min); query(2*k+2,mid+1,r,Max,Min); max2=(*Max); min2=(*Min); (*Max)=max(max1,max2); (*Min)=min(min1,min2); return (*Max)-(*Min); } } int main(){ int i,j,Max,Min; scanf("%d%d",&N,&Q); for(i=1;i<=N;i++) scanf("%d",&cows[i]); build(0,1,N); for(i=0;i<Q;i++){ scanf("%d%d",&A,&B); int res=query( 0,A,B,&Max,&Min ); printf("%d\n",res); } //system("pause"); return 0; }
poj 3264 线段树 寻找最大最小值 SEGMENT TREE
原文:http://blog.csdn.net/taoqick/article/details/18937883