Overview: An off-line algorithm that uses multiplication method to calculate interval maximum, O (nlogn) preprocessing, O (1) access.
Pretreatment:
Status: ST[I][J]:[I,I+2^J) The maximum value between
State transfer: If J equals 0,st[i][j]=0
If J is greater than 0,st[i][j]=max (st[i][j-1],st[i+2^ (j-1)][j-1]) or St[i][j]=min (st[i][j-1],st[i+2^ (j-1)][j-1])
Access:
Find the maximum value in the [L,r] Interval
K=floor (log (r-l+1))
Ans=max (St[l][k],st[r-2^k+1][k]) or Ans=min (St[l][k],st[r-2^k+1][k])
Template:
intst[n][ -],a[n];voidInit_st (intN) { for(inti=n;i>=1; i--) {st[i][0]=A[i]; for(intj=0; i+ (1<<j-1)-1<=n;j++) {St[i][j]=min (st[i][j-1],st[i+ (1<<j-1)][j-1]); } }}intQueryintLintR) { intK=floor (log (r-l+1)/log (2)); returnMin (st[l][k],st[r-(1<<K) +1][k]);}
Example:POJ-3264
Idea: Finding the difference between the interval's value
Code:
#include <iostream>#include<cstdio>#include<string>#include<cmath>#include<algorithm>using namespacestd;#definell Long Long#definePB Push_back#defineMem (A, B) memset (A,b,sizeof (a))Const intn=1e5+5;intss[n][ -],st[n][ -],a[n];voidInit_st (intN) { for(inti=n;i>=1; i--) {st[i][0]=A[i]; ss[i][0]=A[i]; for(intj=1; i+ (1<<j-1)-1<=n;j++) {St[i][j]=min (st[i][j-1],st[i+ (1<<j-1)][j-1]); SS[I][J]=max (ss[i][j-1],ss[i+ (1<<j-1)][j-1]); } }}intQueryintLintR) { intK=floor (log (r-l+1)/log (2)); returnMax (ss[l][k],ss[r-(1<<K) +1][k])-min (st[l][k],st[r-(1<<K) +1][k]);}intMain () {Ios::sync_with_stdio (false); Cin.tie (0); intN,q,l,r; CIN>>n>>Q; for(intI=1; i<=n;i++) cin>>A[i]; Init_st (n); while(q--) {cin>>l>>R; cout<<query (l,r) <<Endl; } return 0;}
View Code
Reference: https://www.cnblogs.com/AireenYe/p/6270518.html
Algorithm Note--st table