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
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
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
线段树大水题
这么简单的题目,比赛的时候居然忘东忘西
受不鸟
题意:
给你N头牛的身高
给你一个范围,输出这个范围内的最高与最矮的差值
代码:
#include <iostream> using namespace std; const int maxn=111111; int sum[maxn<<2]; int minn[maxn<<2]; #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 int Max,Min; void pushup(int rt) { sum[rt]=sum[rt<<1]>sum[rt<<1|1]?sum[rt<<1]:sum[rt<<1|1]; minn[rt]=minn[rt<<1]<minn[rt<<1|1]?minn[rt<<1]:minn[rt<<1|1]; //cout<<sum[rt]<<' '<<minn[rt]<<endl; } void build(int l,int r,int rt) { if(l==r) { scanf("%d",&sum[rt]); minn[rt]=sum[rt]; return; } int m=(l+r)>>1; build(lson); build(rson); pushup(rt); } void query(int l,int r,int rt,int L,int R)//询问 { if(L<=l&&R>=r) { if(Max<sum[rt])Max=sum[rt]; if(Min>minn[rt])Min=minn[rt]; return ; } int m=(l+r)>>1; if(L<=m) query(lson,L,R); if(R>m) query(rson,L,R); } int main() { int t,n,mm,i; int a,b; while(~scanf("%d%d",&n,&mm)) { build(1,n,1); while(mm--) { scanf("%d%d",&a,&b); Max=0,Min=1111110; query(1,n,1,a,b); cout<<Max-Min<<endl; } } return 0; }