TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sparse_table.cpp
Go to the documentation of this file.
1
25#include <array>
26#include <cassert>
27#include <cstdint>
28#include <iostream>
29
34namespace data_structures {
35
41namespace sparse_table {
42
48constexpr uint32_t N = 12345;
49constexpr uint8_t M = 14;
50
52 size_t n = 0;
53
57 std::array<int64_t, N> A = {};
58 std::array<std::array<int64_t, N>, M>
59 ST{};
60 std::array<int64_t, N> LOG = {};
61
69 void buildST() {
70 LOG[0] = -1;
71
72 for (size_t i = 0; i < n; ++i) {
73 ST[0][i] = static_cast<int64_t>(i);
74 LOG[i + 1] = LOG[i] + !(i & (i + 1));
75 }
76
77 for (size_t j = 1; static_cast<size_t>(1 << j) <= n; ++j) {
78 for (size_t i = 0; static_cast<size_t>(i + (1 << j)) <= n; ++i) {
88 int64_t x = ST[j - 1][i];
90 int64_t y =
91 ST[j - 1]
92 [i + (1 << (j - 1))];
94
95 ST[j][i] =
96 (A[x] <= A[y] ? x : y);
98 }
99 }
100 }
101
110 int64_t query(int64_t l, int64_t r) {
111 int64_t g = LOG[r - l + 1];
112 int64_t x = ST[g][l];
114 int64_t y =
115 ST[g][r - (1 << g) + 1];
117
118 return (A[x] <= A[y] ? x : y);
120 }
121};
122} // namespace sparse_table
123} // namespace data_structures
124
129static void test() {
130 /* We take an array as an input on which we need to perform the ranged
131 * minimum queries[RMQ](https://en.wikipedia.org/wiki/Range_minimum_query).
132 */
133 std::array<int64_t, 10> testcase = {
134 1, 2, 3, 4, 5,
135 6, 7, 8, 9, 10};
136 size_t testcase_size =
137 sizeof(testcase) / sizeof(testcase[0]);
138
140 st{};
141
142 std::copy(std::begin(testcase), std::end(testcase),
143 std::begin(st.A));
144 st.n = testcase_size;
145
146 st.buildST();
147
148 // pass queries of the form: [l,r]
149 assert(st.query(1, 9) == 1);
150 assert(st.query(2, 6) == 2);
151 assert(st.query(3, 8) == 3);
152
153 std::cout << "Self-test implementations passed!" << std::endl;
154}
155
162int main(int argc, char *argv[]) {
163 test(); // run self-test implementations
164 return 0;
165}
int main()
Main function.
for IO operations
Functions for Implementation of Sparse Table
constexpr uint32_t N
A struct to represent sparse table for min() as their invariant function, for the given array A....
static void test()
Self-test implementations.
constexpr uint8_t M
ceil(log2(N)).
int64_t query(int64_t l, int64_t r)
Queries the sparse table for the value of the interval [l, r] (i.e. from l to r inclusive).
std::array< int64_t, N > LOG
where floor(log2(i)) are precomputed.
std::array< int64_t, N > A
input array to perform RMQ.
std::array< std::array< int64_t, N >, M > ST
the sparse table storing min() values for given interval.