Created
November 1, 2024 13:57
-
-
Save bruteforceboy/556bacfdf141747dd4b61d16f807bc21 to your computer and use it in GitHub Desktop.
Somewhat Simple Generic SegmentTree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
template <typename T> struct SegmentTree { | |
std::vector<T> st; | |
int n; | |
SegmentTree(int n) { | |
this->n = n; | |
st.resize(4 * n); | |
} | |
template <class B, class C> | |
void update(int idx, T val, B assign_op, C upd_op) { | |
auto do_update = [&](auto &&self, int l, int r, int node) -> void { | |
if (l == r) { | |
st[node] = assign_op(st[node], val); | |
return; | |
} | |
int mid = l + r >> 1; | |
(idx <= mid) ? self(self, l, mid, (node << 1)) | |
: self(self, mid + 1, r, (node << 1) + 1); | |
st[node] = upd_op(st[(node << 1)], st[(node << 1) + 1]); | |
}; | |
do_update(do_update, 0, n - 1, 1); | |
} | |
template <T inf, class B> T query(int l, int r, B op) { | |
auto do_query = [&](auto &&self, int lb, int rb, int node) -> T { | |
if (rb < l || lb > r) | |
return inf; | |
if (lb >= l && rb <= r) | |
return st[node]; | |
int mid = lb + rb >> 1; | |
auto left = self(self, lb, mid, (node << 1)), | |
right = self(self, mid + 1, rb, (node << 1) + 1); | |
return op(left, right); | |
}; | |
return do_query(do_query, 0, n - 1, 1); | |
} | |
}; | |
#define assign [](T x, T y) { return y; } | |
#define min_op [](T x, T y) { return std::min(x, y); } | |
#define max_op [](T x, T y) { return std::max(x, y); } | |
#define sum_op [](T x, T y) { return x + y; } | |
// https://cses.fi/paste/bcc3f84db2725c21a88721/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment