# BZOJ 1699: [Usaco2007 Jan]Balanced Lineup排队

## Input

* 第一行: N 和 Q. * 第2..N+1行: 第i+1行是第i头牛的身高.

* 第N+2..N+Q+1行: 两个整数, A 和 B (1 <= A <= B <= N), 表示从A到B的所有牛.

## Output

*第1..Q行: 所有询问的回答 (最高和最低的牛的身高差), 每行一个.

6 3
1
7
3
4
2
5
1 5
4 6
2 2

## Sample Output

6
3
0

——分隔符——

#include<cstdio>
using namespace std;
struct Btree{
int left;
int right;
int num;
int max;
int min;
};
const int Maxn=50000;
Btree tree[Maxn*4+1];

int height[Maxn+1];

int n,q;

inline int remax(int a,int b){
if (a>b) return a;
return b;
}

inline int remin(int a,int b){
if (a<b) return a;
return b;
}

void build(int x,int left,int right){
tree[x].left=left;
tree[x].right=right;
if (left==right){
tree[x].min=tree[x].max=tree[x].num=height[left];
}else{
int mid=(left+right)/2;
build(x*2,left,mid);
build(x*2+1,mid+1,right);
tree[x].max=remax(tree[x*2].max,tree[x*2+1].max);
tree[x].min=remin(tree[x*2].min,tree[x*2+1].min);
}
}

int queryMax(int x,int left,int right){
if (left<=tree[x].left && tree[x].right<=right){
return tree[x].max;
}else{
int mid=(tree[x].left+tree[x].right)/2;
int maxNum=-1;
if (left<=mid) maxNum=remax(maxNum,queryMax(x*2,left,right));
if (right>=mid+1) maxNum=remax(maxNum,queryMax(x*2+1,left,right));
return maxNum;
}
}

int queryMin(int x,int left,int right){
if (left<=tree[x].left && tree[x].right<=right){
return tree[x].min;
}else{
int mid=(tree[x].left+tree[x].right)/2;
int minNum=2147483647;
if (left<=mid) minNum=remin(minNum,queryMin(x*2,left,right));
if (right>=mid+1) minNum=remin(minNum,queryMin(x*2+1,left,right));
return minNum;
}
}

int main(){
scanf("%d%d",&n,&q);
for (int i=1;i<=n;i++){
scanf("%d",&height[i]);
}
build(1,1,n);
for (;q--;){
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",queryMax(1,l,r)-queryMin(1,l,r));
}

return 0;
} 

posted @ 2014-09-08 10:19  WNJXYK  阅读(154)  评论(0编辑  收藏  举报