1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| #include <iostream> #include <stdio.h> #include <algorithm> #include <string.h> #include <math.h> using namespace std; int t,n,q; long tree1[50010<<2]; long tree2[50010<<2]; long a[50010]; void PushUp(int rt){ tree1[rt] =max(tree1[rt*2] , tree1[rt*2+1]) ; tree2[rt] =min(tree2[rt*2] , tree2[rt*2+1]) ; }
void Build(int l,int r,int rt){ if(l==r){ tree1[rt] = a[l]; tree2[rt] = a[l]; return; } int m=(l+r)/2; Build(l,m,rt*2); Build(m+1,r,rt*2+1); PushUp(rt);
} long MAXQuery(int l,int r,int rt,int L,int R){ if(L <= l && r <= R){ return tree1[rt]; } int m=(l+r)/2; long res=0; if(L<=m) res=max(res,MAXQuery(l,m,rt*2,L,R)); if(m<R) res=max(res,MAXQuery(m+1,r,rt*2+1,L,R)); return res;
} long MINQuery(int l,int r,int rt,int L,int R){ if(L <= l && r <= R){ return tree2[rt]; } int m=(l+r)/2; long res=0x3f3f3f; if(L<=m) res=min(res,MINQuery(l,m,rt*2,L,R)); if(m<R) res=min(res,MINQuery(m+1,r,rt*2+1,L,R)); return res;
}
int main() {
scanf("%d%d",&n,&q); for(int i = 1; i <= n; i++) scanf("%ld", &a[i]); Build(1,n,1); int a,b; while(q--){ scanf("%d%d",&a,&b); cout << MAXQuery(1,n,1,a,b)-MINQuery(1,n,1,a,b) << endl; } return 0; }
|