This is a customizable segment tree class that supports lazy propagation, in an STD-similar way.
Version: 2.2
Last commit: Fix styling
- Fixing the lazy update
- Optimizations for lazy update
- Adding overloads that doesn't need
range
- Adding time in tests
#include <bits/stdc++.h>
using namespace std;
// Put the segment tree templete code here..
using namespace alg;
segment_tree<int, merge_min> st;
// Solution for RMQ problem
int main() {
int n, q;
cin >> n;
st.set_out(INT_MAX);
st.resize(n);
for (int i = 0; i < n; cin >> st.values[i++]);
st.build();
cin >> q;
while (q--) {
int l, r;
cin >> l >> r;
l--, r--; // Zero based
cout << st.get(l, r) << '\n';
}
}
- Adding compare function for
binary_search
- Optimizing the
update_util
&get_util
, by making it iterative instead of recursive.
alg::segment_tree<Type, MergeFunc, UpdateType, LazyUpdate, ExpandLazy> NAME;
Type
: For example (int
,long long
)MergeFunc
: A function that should merge two types (there is predefined ones likemerge_sum
,merge_max
)UpdateType
: The type that stores the update for a segement (could beint
, or a customstruct
that you define)LazyUpdate
: Update a value of a segment depending on anUpdateType
. in the form ofType LazyUpdate(Type x, UpdateType upd)
ExpandLazy
: Getting theUpdateType
from a big segment into smaller segment. in the form ofUpdateType ExpandLazy(UpdateType cur, UpdateType prev)
int size()
: Returns size of the arrayvalues
void resize(int sz)
: Resize the arrayvalues
void clear()
: Clear the segment tree, lazy, andvalues
void set_out(Type out)
: The default value that shouldn't affect the merge function (for example:INT_MIN
in case of finding the maximum)void set_out_update(UpdType out)
: The value that shouldn't be applied when lazy update runs (The value oflazy[node]
if there is no update should be applied onnode
)int binary_search(int k)
: Returns index of first element which has get() >= kType get(range q)
: Returns the merge function of the range.O(log2(size()))
void build()
: Builds the segment tree.O(size())
void update(int idx, Type value)
: Updates a value in the array & segment tree.O(log2(size()))
void lazy_update(range q, UpdType value)
: Updates a range.O(log2(size()))
maxST = 2e5+1
Edit this constant to edit the size of the tree
- The ranges must be zero based
- Use the namespace
alg
- Use
set_out
andset_out_update
beforeresize
- Don't forget to use
build
- Edit
maxST
if you will use a segment tree with a bigger size - You can use
range
structure
- SPOJ: HORRIBLE (in
0.24s
), RMQSQ (in0.21s
) - Codeforces: 52C Circular RMQ (in
0.358s
) - CSES: Range Queries (first 6 problems), Hotel Queries, and Range Updates and Sums (in
0.54s
)