From abf464e844eccf360333c75fd126d726bfab3175 Mon Sep 17 00:00:00 2001 From: indy256 Date: Sun, 8 Oct 2023 14:45:02 -0400 Subject: [PATCH] Improve segment_tree --- cpp/structures/segment_tree.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/cpp/structures/segment_tree.h b/cpp/structures/segment_tree.h index 618d2b5a..6e93d57e 100644 --- a/cpp/structures/segment_tree.h +++ b/cpp/structures/segment_tree.h @@ -9,6 +9,12 @@ 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 +22,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 +59,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([l]); return; } int m = (l + r) >> 1;