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
题目大意: 有一排高度不一的牛(...),现在给出它们的高度,给几个区间求区间内的最高的牛和最矮的牛的“身高差”。
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int INF=10000000;
const int INF1=200005;
struct node{
int l,r;
int zd,zx;
node(){
l=0;r=0;
zd=zx=0;
}
};
struct node tree[INF1*3];
int a[50010];
int MAX,MIN;
void create_tree(int h,int x,int y){
tree[h].l=x;tree[h].r=y;
if(x==y){
tree[h].zd=tree[h].zx=a[x];
return;
}
int mid=(x+y)/2;
create_tree(h*2,x,mid);
create_tree(h*2+1,mid+1,y);
tree[h].zd=max(tree[h*2].zd,tree[h*2+1].zd);
tree[h].zx=min(tree[h*2].zx,tree[h*2+1].zx);
return;
}
void dfs(int h,int x,int y){
if(tree[h].l>y && tree[h].r<x)
return;
if(tree[h].l==x && tree[h].r==y){
MAX=max(tree[h].zd,MAX);
MIN=min(tree[h].zx,MIN);
return;
}
int mid=(tree[h].l+tree[h].r)/2;
if(y<=mid)
dfs(h*2,x,y);
else if(x>mid)
dfs(h*2+1,x,y);
else{
dfs(h*2,x,mid);
dfs(h*2+1,mid+1,y);
}
}
int main(){
int i,j,k,m,n,x,y;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
create_tree(1,1,n);
for(i=1;i<=m;i++){
scanf("%d%d",&x,&y);
MAX=-INF;MIN=INF;
dfs(1,x,y);
printf("%d\n",MAX-MIN);
}
return 0;
}