标签:
<span style="color:#3366ff;">/********************************************************************* author : Grant Yuan time : 2014.7.26 algorithm : 线段树 **********************************************************************/ #include <iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #define MAX 50003 #define INF 999999999 using namespace std; int n,m; struct node{ int l; int r; int Min; int Max; }; int m1,m2; node tree[4*MAX]; int h[MAX]; void build(int left,int right,int root) { tree[root].l=left; tree[root].r=right; if(left==right){ tree[root].Max=h[left]; tree[root].Min=h[left]; return; } int mid=(left+right)>>1; build(left,mid,root*2); build(mid+1,right,root*2+1); tree[root].Max=max(tree[root*2].Max,tree[root*2+1].Max); tree[root].Min=min(tree[root*2].Min,tree[root*2+1].Min); } void findMax(int left,int right,int root) { if(left<=tree[root].l&&right>=tree[root].r) {m1=max(m1,tree[root].Max); return;} int mid=(tree[root].l+tree[root].r)>>1; if(mid>=right) findMax(left,right,root*2); else if(mid<left) findMax(left,right,root*2+1); else{ findMax(left,right,2*root); findMax(left,right,2*root+1); } } void findMin(int left,int right,int root) { if(left<=tree[root].l&&right>=tree[root].r) {m2=min(m2,tree[root].Min); return;} int mid=(tree[root].l+tree[root].r)>>1; if(mid>=right) findMin(left,right,root*2); else if(mid<left) findMin(left,right,root*2+1); else{ findMin(left,right,2*root); findMin(left,right,2*root+1); } } int main() { cin>>n>>m;int a,b; for(int i=1;i<=n;i++) scanf("%d",&h[i]); build(1,n,1); for(int i=0;i<m;i++) {scanf("%d%d",&a,&b); m1=0;m2=INF; findMax(a,b,1); findMin(a,b,1); printf("%d\n",m1-m2); } return 0; } </span>
标签:
原文地址:http://blog.csdn.net/yuanchang_best/article/details/38148561