Title Address: http://poj.org/problem?id=3264
Sample Input
6 31734251 54) 62 2
Sample Output
630
Analysis: Standard template problem, can be written with line segment tree, but with rmq-st to write code relatively short.
What is the difference between the maximum and minimum values for each output interval "L, R".
Notice a place where the code uses the LOG2 () function, but I submit the code in C + + with the <math.h> and <cmath> header files to the POJ feedback is a compilation error.
Changed to g++ submitted before AC. (Note that you do not have to use log2 (), the formula for changing the bottom, the log () function)
Code:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include < math.h> #include <cmath> #include <iostream> #include <string> #include <queue> #include < stack> #include <vector> #include <algorithm> #define N 100000+100using namespace Std;int N, m;int f[n];// POJ 3264int st_max[n][22];int st_min[n][22];void st_prepare () {int i, J; for (I=1; i<=n; i++) {st_min[i][0]=f[i]; St_max[i][0]=f[i]; } for (j=1; (1<<J) <=n; J + +) {for (i=1; i+ (1<<j) -1<=n; i++) {st_min[i][j]=min (st_min[i][j-1], st_min[i+ (1<< (j-1))] [J-1]); St_max[i][j]=max (St_max[i][j-1], st_max[i+ (1<< (j-1))][j-1]); }//Start writing only to find the minimum value, the inner for loop does not write parentheses, resulting in the subsequent addition of the maximum value, run is not correct}//preprocessing//Because of negligence inner layer loop execution two commands but no curly braces,, debug half a day, remember}int rmq_st_min (int li, int ri) {int k=log2 (ri-li+1); return min (St_min[li][k], st_min[ri-(1<<k) +1][k]);} int Rmq_st_max(int li, int ri) {int k=log2 (ri-li+1); Return Max (St_max[li][k], st_max[ri-(1<<k) +1][k]);} int main () {int i, J; scanf ("%d%d", &n, &m); for (I=1; i<=n; i++) scanf ("%d", &f[i]); Set up array st_prepare (); int Li, RI; while (m--) {scanf ("%d%d", &li, &ri); printf ("%d---%d", Rmq_st_max (Li, RI), Rmq_st_min (Li, RI)); printf ("%d\n", Rmq_st_max (Li, RI)-rmq_st_min (Li, RI)); } return 0;}
POJ 3264 Balanced Lineup "rmq-st query interval maximum minimum value difference + template Application"