Algorithm Note--st table

Source: Internet
Author: User

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&LT;&LT;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&LT;&LT;K) +1][k])-min (st[l][k],st[r-(1&LT;&LT;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.