来源:POJ3264
一排牛给高度,给区间求极差。。。看题目那么多废话。。。笑cry。。。
还是由于数量太大,所以必须用线段树。
这里的find要来两个照最大和最小,其他的还是比较好理解的。。。
AC代码(VJ提交):
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
struct Node{
int l,r;
int maxn,minn;
};
Node tree[200000];
int h[50010];
int minn,maxn;
void build(int l,int r ,int root){//建树,话说这已经差不多变成范式了。。。可怕。。。
tree[root].l=l;
tree[root].r=r;
if(l==r){
tree[root].maxn=h[l];
tree[root].minn=h[l];
return ;
}
int mid=(l+r)>>1;
build(l,mid,root*2);
build(mid+1,r,root*2+1);
tree[root].maxn=max(tree[2*root].maxn,tree[2*root+1].maxn);
tree[root].minn=min(tree[2*root].minn,tree[2*root+1].minn);
}
void findmax(int l,int r,int root){//这里无疑是全局maxn的功劳
if(tree[root].l==l&&tree[root].r==r){
if(tree[root].maxn>maxn)
maxn=tree[root].maxn;
return ;
}
int mid=(tree[root].l+tree[root].r)/2;
if(mid>=r)
findmax(l,r,root*2);
else if(mid<l)
findmax(l,r,root*2+1);
else {
findmax(l,mid,root*2);
findmax(mid+1,r,root*2+1);
}
}
void findmin(int l,int r,int root){
if(tree[root].l==l&&tree[root].r==r){
if(tree[root].minn<minn)
minn=tree[root].minn;
return ;
}
int mid=(tree[root].l+tree[root].r)/2;
if(mid>=r)
findmin(l,r,root*2);
else if(mid<l){
findmin(l,r,root*2+1);
}
else {
findmin(l,mid,root*2);
findmin(mid+1,r,root*2+1);
}
}
int main(){
int n,m;
int i;
scanf("%d%d",&n,&m);
memset(h,0,sizeof(h));
for(i=1;i<=n;i++)
scanf("%d",&h[i]);
build(1,n,1);
while(m--){
int a,b;
maxn=0;
minn=99999999;
scanf("%d%d",&a,&b);
findmax(a,b,1);
findmin(a,b,1);
printf("%d\n",maxn-minn);
}
return 0;
}