http://poj.org/problem?id=3264
Test instructions: The existing n numbers, asking you what is the difference between the maximum and minimum values in the interval [a, b]?
Analysis: Line tree template, but need to have two queries, a query in the maximum value of the interval, a query in the minimum value of the interval, and finally subtract the results.
#include <iostream>#include<stdio.h>#include<string.h>#include<string>#include<vector>#include<algorithm>#include<map>#include<queue>#include<stack>#include<math.h>using namespacestd;#defineMet (A, b) memset (A, B, sizeof (a))#defineMAXN 51000#defineINF 0x3f3f3f3fConst intMOD = 1e9+7; typedefLong LongLL;#defineLson rt<<1#defineRson rt<<1|1intA[MAXN], N;structnode{intL, R, Maxs, mins;} TREE[MAXN<<2];voidBuildintLintRintRT) {TREE[RT].L=l; TREE[RT].R=R; if(L = =r) {Tree[rt].maxs=A[l]; Tree[rt].mins=A[l]; return ; } intMid = (l+r)/2; Build (L, Mid, Lson); Build (Mid+1, R, Rson); Tree[rt].maxs=Max (TREE[LSON].MAXS, TREE[RSON].MAXS); Tree[rt].mins=min (tree[lson].mins, tree[rson].mins);}intQuery1 (intLintRintRT) { if(Tree[rt].l==l && tree[rt].r==R)returnTree[rt].maxs; intMid = (TREE[RT].L+TREE[RT].R)/2; if(R<=mid)returnQuery1 (L, R, Lson); Else if(L>mid)returnQuery1 (L, R, Rson); Else { intLMAXS =Query1 (L, Mid, Lson); intRmaxs = Query1 (mid+1, R, Rson); intMaxs =Max (LMAXS, RMAXS); returnMaxs; }}intQuery2 (intLintRintRT) { if(Tree[rt].l==l && tree[rt].r==R)returnTree[rt].mins; intMid = (TREE[RT].L+TREE[RT].R)/2; if(R<=mid)returnQuery2 (L, R, Lson); Else if(L>mid)returnQuery2 (L, R, Rson); Else { intLmins =Query2 (L, Mid, Lson); intRmins = Query2 (mid+1, R, Rson); intmins =min (lmins, rmins); returnmins; }}intMain () {intQ, A, B; while(SCANF ("%d%d", &n, &q)! =EOF) { for(intI=1; i<=n; i++) scanf ("%d", &A[i]); Build (1N1); while(Q--) {scanf ("%d%d", &a, &b); intp = Query1 (A, B,1);///Query Maximum Value intQ = Query2 (A, B,1);///Query Minimum Valueprintf ("%d\n", P-q); } } return 0;}
View Code
Balanced Lineup POJ 3264 (segment tree)