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
18
19
#include <cassert>
20
#include <iostream>
21
#include <vector>
22
27
namespace
range_queries
{
32
namespace
prefix_sum_array
{
33
34
std::vector<int64_t> PSA{};
35
41
void
build
(
const
std::vector<int64_t>& original_array) {
42
PSA.clear();
43
PSA.push_back(0);
44
for
(std::size_t i = 1; i < original_array.size(); ++i) {
45
PSA.push_back(PSA.back() + original_array[i]);
46
}
47
}
48
54
int64_t
query
(int64_t beg, int64_t end) {
return
PSA[end] - PSA[beg - 1]; }
55
56
}
// namespace prefix_sum_array
57
}
// namespace range_queries
58
63
static
void
test
() {
64
std::vector<int64_t> values{0, 123, 0, 2, -2, 5,
65
24, 0, 23, -1, -1};
// original array
66
67
range_queries::prefix_sum_array::build
(values);
68
// queries are of the type: sum of the range [a, b] = psa[b] - psa[a-1]
69
70
assert(
range_queries::prefix_sum_array::query
(1, 10) ==
71
173);
// sum of the entire array
72
assert(
range_queries::prefix_sum_array::query
(4, 6) ==
73
27);
// the sum of the interval [4, 6]
74
assert(
range_queries::prefix_sum_array::query
(5, 9) ==
75
51);
// the sum of the interval [5, 9]
76
}
77
82
int
main
() {
83
test
();
// run self-test implementations
84
return
0;
85
}
prefix_sum_array
Range sum queries using prefix-sum-array.
range_queries
for std::vector
Definition
fenwick_tree.cpp:28
range_queries::prefix_sum_array::query
int64_t query(int64_t beg, int64_t end)
query function
Definition
prefix_sum_array.cpp:54
range_queries::prefix_sum_array::build
void build(const std::vector< int64_t > &original_array)
function that builds the PSA
Definition
prefix_sum_array.cpp:41
test
static void test()
Self-test implementations.
Definition
prefix_sum_array.cpp:63
main
int main()
Main function.
Definition
prefix_sum_array.cpp:82
range_queries
prefix_sum_array.cpp
Generated by
1.14.0