TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sparse_table_range_queries.cpp
1
17#include <algorithm>
18#include <cassert>
19#include <iostream>
20#include <vector>
21
26namespace range_queries {
31namespace sparse_table {
37template <typename T>
38std::vector<T> computeLogs(const std::vector<T>& A) {
39 int n = A.size();
40 std::vector<T> logs(n);
41 logs[1] = 0;
42 for (int i = 2; i < n; i++) {
43 logs[i] = logs[i / 2] + 1;
44 }
45 return logs;
46}
47
55template <typename T>
56std::vector<std::vector<T> > buildTable(const std::vector<T>& A,
57 const std::vector<T>& logs) {
58 int n = A.size();
59 std::vector<std::vector<T> > table(20, std::vector<T>(n + 5, 0));
60 int curLen = 0;
61 for (int i = 0; i <= logs[n]; i++) {
62 curLen = 1 << i;
63 for (int j = 0; j + curLen < n; j++) {
64 if (curLen == 1) {
65 table[i][j] = A[j];
66 } else {
67 table[i][j] =
68 std::min(table[i - 1][j], table[i - 1][j + curLen / 2]);
69 }
70 }
71 }
72 return table;
73}
74
83template <typename T>
84int getMinimum(int beg, int end, const std::vector<T>& logs,
85 const std::vector<std::vector<T> >& table) {
86 int p = logs[end - beg + 1];
87 int pLen = 1 << p;
88 return std::min(table[p][beg], table[p][end - pLen + 1]);
89}
90} // namespace sparse_table
91} // namespace range_queries
92
96int main() {
97 std::vector<int> A{1, 2, 0, 3, 9};
98 std::vector<int> logs = range_queries::sparse_table::computeLogs(A);
99 std::vector<std::vector<int> > table =
100 range_queries::sparse_table::buildTable(A, logs);
101 assert(range_queries::sparse_table::getMinimum(0, 0, logs, table) == 1);
102 assert(range_queries::sparse_table::getMinimum(0, 4, logs, table) == 0);
103 assert(range_queries::sparse_table::getMinimum(2, 4, logs, table) == 0);
104 return 0;
105}
int main()
Main function.
for std::vector
Functions for Implementation of Sparse Table