Luo Gu P3865 [template] ST ST table table

URL: https://www.luogu.org/problem/P3865

Meaning of the questions:

Static interval maximum value and needs $ O (nlgn) $ pretreatment, $ O (1) $ query.

answer:

Table established ST, ST table is a data structure for quick multiplication value based on the most section, which consists of a two-dimensional array of size $ O (nlgn) $ configuration, with $ st [i] [j] $ represents $ the $ j to $ j + 2 ^ {i-1} $ maximum value, $ j $ to $ j + 2 ^ length {i-1} $ is $ 2 ^ i $, then half the length is equal to $ 2 ^ {i-1} $, then the first half of the state is represented as $ st [i-1] [j] $. The length of the second half is also $ 2 ^ {i-1} $, the starting position is $ j + 2 ^ {i-1} $. Then the state of the second half is represented as $ st [i-1] [j + 2 ^ {i-1}] $. Therefore: $ st [i] [j] = ope (st [i-1] [j], st [i-1] [j + 2 ^ {i-1}]) $.

Then the query is: we understand the following theorem: $ 2 ^ {log (a ) +1}> a $, then we want to query the most value $ L $ $ $ R & lt's. Provided $ len = r-l + 1 , t = log (len) $, according to the above theorem: $ 2 ^ t> len / 2 $, so the position is, $ l + 2 ^ t $ crossed $ L $ to the middle of the $ r $! Since the position halfway through, so $ L $ to $ R & lt $ maximum value may be represented as $ OPE $ (from $ L $ next $ 2 ^ t $ maximum value from $ R & lt $ Previous $ 2 ^ t $ most value), the foregoing state is represented as $ st [t] [l] $. Disposed behind (forward $ 2 ^ t Extreme Value $ from $ R & lt $) initial position is $ k $, then the $ k + 2 ^ t-1 = r $, so $ k = r-2 ^ t + 1 $ , so that the latter state is represented as $ st [t] [r- 2 ^ t + 1] $, so to $ $ $ L $ R & lt expressed as the minimum $ ope (st [t] [ l], st [t ] [r-2 ^ t + 1]) $, so the query time complexity is $ O (1) $. (Reference blog: https://blog.csdn.net/Hanks_o/article/detail/77547380 )

AC Code:

#include <the iostream> 
#include <the cmath> 
#include <cstdio> 
int NUM [1000005]; 
int ST [25] [1000005]; // length i starting position j minimum 
#define max (a, b ?) (A> B A: B) 
the using namespace STD; 
void the init (int n-) 
{ 
    for (int I =. 1; I <= n-; ++ I) 
        Scanf ( "% D", & NUM [I]); 
    for (int I =. 1; I <= n-; I ++) 
        ST [0] [I] = NUM [I]; 
    for (int I =. 1; (I <<. 1) <= n-; I ++) 
    { 
        for (int. 1 = J; J <= n-; J ++) // J + (<<. 1 I) is the beginning of a period, the period of -1 means the end 
            if (j + (1 << i ) -1 < = n-) 
                ST [I] [J] = max (ST [I-. 1] [J], ST [I-. 1] [J + (. 1 << (I-. 1))]); 
    } 
} 
int Query (int l,int r)
{
    int k=int(log2(r-l+1)/log2(2.0));
    return max(st[k][l],st[k][r-(1<<k)+1]);
}
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    init(n);
    int a,b;
    for(int i=0;i<m;++i)
    {
        scanf("%d%d",&a,&b);
        printf("%d\n",query(a,b));
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/Aya-Uchida/p/11325263.html