From 15c11cbcdbbc9da102b0b917b963c7574f3d8b0e Mon Sep 17 00:00:00 2001 From: theSoberSobber <109434814+theSoberSobber@users.noreply.github.com> Date: Sat, 3 Feb 2024 23:29:28 +0530 Subject: [PATCH] segtree general --- codes/Segtree-General.cpp | 73 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 codes/Segtree-General.cpp diff --git a/codes/Segtree-General.cpp b/codes/Segtree-General.cpp new file mode 100644 index 0000000..52048c3 --- /dev/null +++ b/codes/Segtree-General.cpp @@ -0,0 +1,73 @@ +//Segtree-General +//General segree, needs node struct (with members def and epsilon(default) for all of them) and operation lambda (merge) + +template +class segtree +{ +public: + // 0 based indexing + // def= default value + vector t; + int n; + T def; + function merge; + void build(int _n, T _def, function _fx) + { + n = _n; + def = _def; + merge = _fx; + t.assign(n * 2, def); + for (int i = n - 1; i; i--) + t[i] = merge(t[i * 2], t[i * 2 + 1]); + } + void build(vector &a, T _def, function _fx) + { + n = a.size(); + def = _def; + merge = _fx; + t.assign(n * 2, def); + for (int i = 0; i < n; i++) + t[i + n] = T(a[i]); + for (int i = n - 1; i; i--) + t[i] = merge(t[i * 2], t[i * 2 + 1]); + } + void update(int i, T v) + { + for (t[i += n] = T(v); i;) + { + i /= 2; + t[i] = merge(t[i * 2], t[i * 2 + 1]); + } + } + // this query is made on [l, r] + T query(int l, int r) + { + T lans = def, rans = def; + for (l += n, r += n + 1; l < r; l /= 2, r /= 2) + { + if (l % 2) + lans = merge(lans, t[l++]); + if (r % 2) + rans = merge(t[--r], rans); + } + return merge(lans, rans); + } +}; + +// demo usage +struct node +{ + int val; + node(int x) + { + val = x; + } + // default value + node() + { + val = 1e18; + } +}; + +segtree seg; +seg.build(n + 1, node(), [&](node x, node y){ return node(min(x.val, y.val)); });