This algorithm can be used to deal with the interval maximum problem, the preprocessing time is O (nlogn), the query time is O (1)
This algorithm is mainly based on the multiplication idea, using the array st[i][j] to indicate the maximum value of the J-th square that starts to search backwards from the first element I 2
Available in recursive way:St[i][j]=min/max (st[i][j-1],st[i+1<< (j-1)][j-1])
The following template takes the interval maximum value as an example
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <ctime>
#include <vector>
#include <set>
#include <map>
#include <stack>
using namespace std;
int st[100010][22];
int a[100010];
int main ()
{int n,m,i,j,k,x,y;
scanf ("%d%d", &n,&m);
For (i=1;i<=n;i++) {
scanf ("%d", &a[i]);
St[i][0]=a[i];
}
For (j=1; (1<<j) <=n;j++)
For (i=1;i+ (1<<j) -1<=n;i++) {
St[i][j]=max (st[i][j-1],st[i+ (1<< (j-1))][j-1]);
}
For (i=1;i<=m;i++) {
scanf ("%d%d", &x,&y);
k=0;
while ((1<< (k+1)) <=y-x+1) k++;
printf ("%d\n", Max (st[x][k],st[y-(1<<k) +1][k]));
Be careful to enclose the 1<<k in parentheses, otherwise it will WA.
Note Add a
}
return 0;
}
ST Table Algorithm for RMQ