TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
prefix_sum_array.cpp File Reference

Prefix Sum Array data structure implementation. More...

#include <cassert>
#include <iostream>
#include <vector>
Include dependency graph for prefix_sum_array.cpp:

Go to the source code of this file.

Namespaces

namespace  range_queries
 for std::vector
namespace  prefix_sum_array
 Range sum queries using prefix-sum-array.

Functions

void range_queries::prefix_sum_array::build (const std::vector< int64_t > &original_array)
 function that builds the PSA
int64_t range_queries::prefix_sum_array::query (int64_t beg, int64_t end)
 query function
static void test ()
 Self-test implementations.
int main ()
 Main function.

Variables

std::vector< int64_t > range_queries::prefix_sum_array::PSA {}

Detailed Description

Prefix Sum Array data structure implementation.

Prefix Sum Array is a data structure, that allows answering sum in some range queries. It can answer most sum range queries in O(1), with a build time complexity of O(N). But it hasn't an update querie.

Definition in file prefix_sum_array.cpp.

Function Documentation

◆ build()

void range_queries::prefix_sum_array::build ( const std::vector< int64_t > & original_array)

function that builds the PSA

Parameters
original_arrayoriginal array of values
Returns
void

Definition at line 41 of file prefix_sum_array.cpp.

41 {
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}

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 82 of file prefix_sum_array.cpp.

82 {
83 test(); // run self-test implementations
84 return 0;
85}
static void test()
Self-test implementations.

◆ query()

int64_t range_queries::prefix_sum_array::query ( int64_t beg,
int64_t end )

query function

Parameters
begbegin of the interval to sum
endend of the interval to sum
Returns
sum of the range [beg, end]

Definition at line 54 of file prefix_sum_array.cpp.

54{ return PSA[end] - PSA[beg - 1]; }

◆ test()

void test ( )
static

Self-test implementations.

Returns
void

Definition at line 63 of file prefix_sum_array.cpp.

63 {
64 std::vector<int64_t> values{0, 123, 0, 2, -2, 5,
65 24, 0, 23, -1, -1}; // original array
66
68 // queries are of the type: sum of the range [a, b] = psa[b] - psa[a-1]
69
71 173); // sum of the entire array
73 27); // the sum of the interval [4, 6]
75 51); // the sum of the interval [5, 9]
76}
int64_t query(int64_t beg, int64_t end)
query function
void build(const std::vector< int64_t > &original_array)
function that builds the PSA

Variable Documentation

◆ PSA

std::vector<int64_t> range_queries::prefix_sum_array::PSA {}

Definition at line 34 of file prefix_sum_array.cpp.

34{};