TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
prefix_sum_array.cpp
Go to the documentation of this file.
1
19#include <cassert>
20#include <iostream>
21#include <vector>
22
27namespace range_queries {
32namespace prefix_sum_array {
33
34std::vector<int64_t> PSA(1, 0);
35
41void build(std::vector<int64_t> original_array) {
42 for (int i = 1; i <= static_cast<int>(original_array.size()); i++) {
43 PSA.push_back(PSA[i - 1] + original_array[i]);
44 }
45}
52int64_t query(int64_t beg, int64_t end) { return PSA[end] - PSA[beg - 1]; }
53
54} // namespace prefix_sum_array
55} // namespace range_queries
56
61static void test() {
62 std::vector<int64_t> values{0, 123, 0, 2, -2, 5,
63 24, 0, 23, -1, -1}; // original array
64
65 range_queries::prefix_sum_array::build(values);
66 // queries are of the type: sum of the range [a, b] = psa[b] - psa[a-1]
67
68 assert(range_queries::prefix_sum_array::query(1, 10) ==
69 173); // sum of the entire array
70 assert(range_queries::prefix_sum_array::query(4, 6) ==
71 27); // the sum of the interval [4, 6]
72 assert(range_queries::prefix_sum_array::query(5, 9) ==
73 51); // the sum of the interval [5, 9]
74}
75
80int main() {
81 test(); // run self-test implementations
82 return 0;
83}
Range sum queries using prefix-sum-array.
for std::vector
static void test()
Self-test implementations.
void build(std::vector< int64_t > original_array)
function that builds the PSA
int main()
Main function.
Definition mo.cpp:9