TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
segment_tree.cpp
Go to the documentation of this file.
1
15#include <iostream>
16#include <vector>
17#include <algorithm>
18#include <cassert>
19
20/*
21 * @namespace
22 * @brief Data structures
23 */
24namespace data_structures {
29template <class T>
31private:
32 const T ID = 0;
33 std::vector<T> t;
34 int size = 0;
35private:
42 T comb(T x, T y) {
43 return x + y;
44 }
51 int mid(int l, int r) {
52 return l + (r - l) / 2;
53 }
62 void update(int i, int l, int r, int pos, T val) {
63 if(l == r) t[i] = val;
64 else {
65 int m = mid(l, r);
66 if(pos <= m) update(i * 2, l, m, pos, val);
67 else update(i * 2 + 1, m + 1, r, pos, val);
68 t[i] = comb(t[i * 2], t[i * 2 + 1]);
69 }
70 }
80 T range_comb(int i, int l, int r, int tl, int tr) {
81 if(l == tl && r == tr) return t[i];
82 if(tl > tr) return 0;
83 int m = mid(l, r);
84 return comb(range_comb(i * 2, l, m, tl, std::min(tr, m)), range_comb(i * 2 + 1, m + 1, r, std::max(tl, m + 1), tr));
85 }
86public:
87 SegmentTree(int n) : t(n * 4, ID), size(n) {}
93 void update(int pos, T val) {
94 update(1, 1, size, pos, val);
95 }
102 T range_comb(int l, int r) {
103 return range_comb(1, 1, size, l, r);
104 }
105};
106} // namespace data_structures
107
112static void test() {
114 t.update(1, 1);
115 t.update(2, 2);
116 t.update(3, 3);
117 t.update(4, 4);
118 t.update(5, 5);
119 assert(t.range_comb(1, 3) == 6); // 1 + 2 + 3 = 6
120 t.update(1, 3);
121 assert(t.range_comb(1, 3) == 8); // 3 + 2 + 3 = 8
122
123 std::cout << "All tests have successfully passed!\n";
124}
125
130int main() {
131 test(); // run self-test implementations
132 return 0;
133}
class representation of the segment tree
const T ID
Comb(ID, x) = x.
int size
Number of elements available for querying in the tree.
T range_comb(int l, int r)
Returns comb across all values between l and r.
void update(int i, int l, int r, int pos, T val)
Helper method for update method below.
int mid(int l, int r)
Gives the midpoint between two integers.
std::vector< T > t
Vector to represent the tree.
T comb(T x, T y)
Any associative function that combines x and y.
T range_comb(int i, int l, int r, int tl, int tr)
Helper method for range_comb method below.
void update(int pos, T val)
Updates a value at a certain position.
for IO operations
static void test()
Self-test implementations.
int main()
Main function.