From 2151a1b3f65081f04cbfe6ff224d9793a485cbe1 Mon Sep 17 00:00:00 2001 From: Andrei Navumenka Date: Sun, 8 Oct 2023 15:14:45 -0400 Subject: [PATCH] Improve segment_tree (#184) --- cpp/structures/segment_tree.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cpp/structures/segment_tree.h b/cpp/structures/segment_tree.h index 618d2b5a..e9a2f3ea 100644 --- a/cpp/structures/segment_tree.h +++ b/cpp/structures/segment_tree.h @@ -9,6 +9,10 @@ struct segtree { long long sum = 0; long long add = 0; + // set initial value for a leave + void initialize(long long v) { mx = v; } + + // apply aggregate operation to the node void apply(int l, int r, long long v) { mx += v; sum += (r - l + 1) * v; @@ -16,6 +20,7 @@ struct segtree { } }; + // construct a node from its children static node unite(const node &a, const node &b) { node res; res.mx = max(a.mx, b.mx); @@ -52,7 +57,7 @@ struct segtree { template void build(int x, int l, int r, const vector &v) { if (l == r) { - tree[x].apply(l, r, v[l]); + tree[x].initialize(v[l]); return; } int m = (l + r) >> 1;