RMQ algorithm uses ST table implementation

RMQ


RMQ (Range Minimum Query), refers to the minimum required interval. Seeking common method is the minimum interval violence.

For a number of columns:
\ [A_1, A_2 ~, ~ A_3, ~ \ cdots, A_n ~ \]
for a given interval \ ([L, R & lt ~], ~ ≤R ≤ n-1 ≦ L \) , \ ( \ min \ {A_l, A_ { l + 1}, cdots, A_r \ \} \) calculation is RMQ problem.

This solution is \ (\ text {Sparse-Table } \) solution, referred to as \ (ST \) table.

  • Pretreatment: The pretreatment is performed for the data \ (n \ log n \) complexity of the processing time

    Order \ (d (i, j) \) of \ (A_i, A_ {i + 1}, \ cdots, A_ {i + 2 ^ j - 1} \) is the minimum value, i.e., \ (d (i, j ) \) interval length of \ (2 ^ J \) , where the multiplication is used thought.

    The \ (d (i, j - 1) \) of \ (A_i, A_ {1 + 1}, \ cdots, A_ {i + 2 ^ {j - 1} -1} \) the minimum value, the interval length is \ (2 ^ {j-1 } \)

    Likewise \ (d (i + 2 ^ {j - 1}, j - 1) \) represents the \ (A_ {i + 2 ^ {j-1}}, A_ {i + 2 ^ {j - 1 +. 1}}, \ cdots, A_ ^ 2 {{I + J + 2}. 1-J ^ {-}. 1 -. 1 J = I ^ 2 + -. 1} \) .

    It is obvious: \ (D (I, J) \) can be expressed as:
    \ [D (I, J) = \ min \ {D (I, J -. 1), ~ D (I + 2 ^ {J -. 1 }, j - 1) \} \]

  • Inquire:

    Order \ (K \) to satisfy \ (2 ^ k ≤ R - L + 1 \) is the largest integer that \ (k = \ max \ { t ~ | ~ 2 ^ t ≤ R - L + 1, t \ in \ mathbb the Z ^ + \} \) .

    Likewise: \ (K = [\ log_2 (RL +. 1)] \) , thus: \ (\ OperatorName {Query} (L, R & lt) = \ min \ {D (L, K), ~ D (R & lt - 2 ^ k + 1, k \ } \)

    The time complexity of the query is \ (O (1) \) .

Note : Because each \ (pow (2, x) \) is a waste of time, in internal binary computer can be expressed as: \ (the X-<< 1 \) .

Code:

namespace RMQ {
    
    void init(int n) {
        for (int i = 1; i <= n; i ++) d[i][0] = a[i];
                for (int j = 1; (1 << j) <= n; j ++) {
            for (int i = 1; i + (1 << j) - 1 <= n; i ++) {
                                d[i][j] = min(d[i][j - 1], d[i + (1 << (j - 1))][j - 1]);
    }
          
        int query(int l, int r) {
        int k = log2(r - l + 1);
        return min(d[l][k], d[r - (1 << k) + 1][k]);
    }
          
}

Note : initthe cycle can not be reversed in order, apparent, (J \) \ value, i.e., the length of the interval to be small to large.

Guess you like

Origin www.cnblogs.com/jeffersonqin/p/11210907.html