Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_fenwick_tree.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
67# ifndef TPL_FENWICK_TREE_H
68# define TPL_FENWICK_TREE_H
69
70# include <bit>
71# include <cassert>
72# include <concepts>
73# include <initializer_list>
74# include <type_traits>
75# include <vector>
76# include <utility>
77# include <ah-concepts.H>
78# include <tpl_array.H>
79# include <tpl_dynList.H>
80# include <ahFunction.H>
81# include <ah-errors.H>
82
83namespace Aleph
84{
89 template <typename T>
91 std::is_arithmetic_v<T> &&
92 std::totally_ordered<T> &&
93 std::is_signed_v<T> &&
94 !std::same_as<T, bool>;
95
102 template <typename F, typename T>
104
135 template <typename T,
136 class Plus = Aleph::plus<T>,
137 class Minus = Aleph::minus<T>>
140 {
141 protected:
142 Array<T> tree; // 1-indexed internal storage (position 0 unused)
143 size_t n = 0; // number of logical elements (0-indexed: 0..n-1)
144
147
153 static constexpr size_t lowbit(size_t x) noexcept
154 {
155 return x & (~x + 1);
156 }
157
160 void build()
161 {
162 for (size_t i = 1; i <= n; ++i)
163 if (const size_t parent = i + lowbit(i); parent <= n)
164 tree(parent) = plus_op(tree(parent), tree(i));
165 }
166
168 template <class F>
169 void fill_from_indexed(F getter)
170 {
171 for (size_t i = 0; i < n; ++i)
172 tree(i + 1) = getter(i);
173 build();
174 }
175
177 template <class StdIt>
178 void fill_from_std_iter(StdIt first, StdIt last)
179 {
180 size_t i = 1;
181 for (; first != last; ++first)
182 tree(i++) = *first;
183 build();
184 }
185
187 template <class AlephIt>
188 void fill_from_aleph_it(AlephIt it)
189 {
190 size_t i = 1;
191 for (; it.has_curr(); it.next_ne())
192 tree(i++) = it.get_curr();
193 build();
194 }
195
196 public:
198 using Item_Type = T;
199
207 Gen_Fenwick_Tree(const size_t num,
208 Plus pop = Plus(), Minus mop = Minus())
209 : tree(num + 1, T()), n(num),
210 plus_op(pop), minus_op(mop)
211 {
212 // empty — all elements are identity
213 }
214
223 Gen_Fenwick_Tree(std::initializer_list<T> il,
224 Plus pop = Plus(), Minus mop = Minus())
225 : tree(il.size() + 1, T()), n(il.size()),
226 plus_op(pop), minus_op(mop)
227 {
228 fill_from_std_iter(il.begin(), il.end());
229 }
230
238 Plus pop = Plus(), Minus mop = Minus())
239 : tree(values.size() + 1, T()), n(values.size()),
240 plus_op(pop), minus_op(mop)
241 {
242 fill_from_indexed([&values](size_t i) { return values(i); });
243 }
244
254 Gen_Fenwick_Tree(const std::vector<T> & values,
255 Plus pop = Plus(), Minus mop = Minus())
256 : tree(values.size() + 1, T()), n(values.size()),
257 plus_op(pop), minus_op(mop)
258 {
259 fill_from_indexed([&values](size_t i) { return values[i]; });
260 }
261
269 Plus pop = Plus(), Minus mop = Minus())
270 : tree(values.size() + 1, T()), n(values.size()),
271 plus_op(pop), minus_op(mop)
272 {
273 fill_from_aleph_it(values.get_it());
274 }
275
279 Gen_Fenwick_Tree(const Gen_Fenwick_Tree & other) = default;
280
291 noexcept(std::is_nothrow_move_constructible_v<Plus>
292 and std::is_nothrow_move_constructible_v<Minus>)
293 : tree(std::move(other.tree)), n(std::exchange(other.n, 0)),
294 plus_op(std::move(other.plus_op)), minus_op(std::move(other.minus_op))
295 {}
296
302 Gen_Fenwick_Tree &operator=(const Gen_Fenwick_Tree & other) = default;
303
309 Gen_Fenwick_Tree &operator=(Gen_Fenwick_Tree && other) noexcept(noexcept(swap(other)))
310 {
311 swap(other);
312 return *this;
313 }
314
321 void update(size_t i, const T & delta)
322 {
324 << "Gen_Fenwick_Tree::update: index " << i << " >= size " << n;
325
326 for (++i; i <= n; i += i & (-i))
327 tree(i) = plus_op(tree(i), delta);
328 }
329
336 T prefix(size_t i) const
337 {
339 << "Gen_Fenwick_Tree::prefix: index " << i << " >= size " << n;
340
341 T s = T();
342 for (++i; i > 0; i -= i & (-i))
343 s = plus_op(s, tree(i));
344 return s;
345 }
346
354 T query(const size_t l, const size_t r) const
355 {
357 << "Gen_Fenwick_Tree::query: r=" << r << " >= n=" << n;
359 << "Gen_Fenwick_Tree::query: l=" << l << " > r=" << r;
360
361 return l > 0 ? minus_op(prefix(r), prefix(l - 1)) : prefix(r);
362 }
363
371 T get(const size_t i) const
372 {
373 return query(i, i);
374 }
375
384 void set(const size_t i, const T & value)
385 {
386 update(i, minus_op(value, get(i)));
387 }
388
390 [[nodiscard]] constexpr size_t size() const noexcept { return n; }
391
393 [[nodiscard]] constexpr bool is_empty() const noexcept { return n == 0; }
394
400 {
401 auto ret = Array<T>::create(n);
402 for (size_t i = 0; i < n; ++i)
403 ret(i) = get(i);
404 return ret;
405 }
406
416 void swap(Gen_Fenwick_Tree & other)
417 noexcept(std::is_nothrow_swappable_v<Plus> and std::is_nothrow_swappable_v<Minus>)
418 {
419 // the operations first, so that one whose swap throws leaves no
420 // array with the operations of the other
421 swap_operations(other);
422 tree.swap(other.tree);
423 std::swap(n, other.n);
424 }
425
426 private:
427 // The additions and the subtractions, with the swaps that the
428 // specification of swap() evaluates (found by their arguments, else
429 // std::swap()), both or none: if that of the subtractions throws, the
430 // additions are exchanged back
432 {
433 using std::swap;
434 swap(plus_op, other.plus_op);
435 try
436 {
437 swap(minus_op, other.minus_op);
438 }
439 catch (...)
440 {
441 swap(plus_op, other.plus_op);
442 throw;
443 }
444 }
445 };
446
447
467 template <FenwickArithmetic T>
469 : public Gen_Fenwick_Tree<T, Aleph::plus<T>, Aleph::minus<T>>
470 {
472 using Base::Base; // inherit all constructors
473
489 size_t find_kth(T k) const requires std::integral<T>
490 {
491 const size_t nn = this->n;
492 if (nn == 0)
493 return 0;
494
495 size_t pos = 0;
496 // highest power of 2 that is <= nn
497 size_t bit_mask = std::bit_floor(nn);
498
499 while (bit_mask > 0)
500 {
501 if (const size_t next = pos + bit_mask; next <= nn && this->tree(next) < k)
502 {
503 k -= this->tree(next);
504 pos = next;
505 }
506 bit_mask >>= 1;
507 }
508
509 return pos < nn ? pos : nn;
510 }
511 };
512
553 template <FenwickArithmetic T>
555 {
556 Gen_Fenwick_Tree<T> b1; // stores differences d[i]
557 Gen_Fenwick_Tree<T> b2; // stores d[i] * i
558 size_t n = 0;
559
561 T prefix_sum(size_t i) const
562 {
563 return static_cast<T>(i + 1) * b1.prefix(i) - b2.prefix(i);
564 }
565
568 {
569 auto d2 = Array<T>::create(n);
570 d2(0) = T();
571 for (size_t i = 1; i < n; ++i)
572 d2(i) = d(i) * static_cast<T>(i);
573
574 Gen_Fenwick_Tree<T> new_b1(d);
575 Gen_Fenwick_Tree<T> new_b2(d2);
576 b1.swap(new_b1);
577 b2.swap(new_b2);
578 }
579
580 public:
581 using Item_Type = T;
582
584 Range_Fenwick_Tree(const size_t num)
585 : b1(num), b2(num), n(num)
586 {
587 // empty — all elements are identity
588 }
589
598 Range_Fenwick_Tree(std::initializer_list<T> il)
599 : b1(il.size()), b2(il.size()), n(il.size())
600 {
601 if (n == 0)
602 return;
603
604 auto d = Array<T>::create(n);
605 auto it = il.begin();
606 d(0) = *it;
607 T prev = *it++;
608 for (size_t i = 1; i < n; ++i, ++it)
609 {
610 d(i) = *it - prev;
611 prev = *it;
612 }
614 }
615
621 : b1(values.size()), b2(values.size()), n(values.size())
622 {
623 if (n == 0)
624 return;
625
626 auto d = Array<T>::create(n);
627 d(0) = values(0);
628 for (size_t i = 1; i < n; ++i)
629 d(i) = values(i) - values(i - 1);
631 }
632
636 Range_Fenwick_Tree(const Range_Fenwick_Tree & other) = default;
637
646 : b1(std::move(other.b1)), b2(std::move(other.b2)), n(std::exchange(other.n, 0))
647 {}
648
655
662 {
663 swap(other);
664 return *this;
665 }
666
675 void update(size_t l, const size_t r, const T & delta)
676 {
678 << "Range_Fenwick_Tree::update: l=" << l << " > r=" << r;
680 << "Range_Fenwick_Tree::update: r=" << r << " >= size " << n;
681
682 b1.update(l, delta);
683 b2.update(l, delta * static_cast<T>(l));
684
685 if (r + 1 < n)
686 {
687 T neg = -delta;
688 b1.update(r + 1, neg);
689 b2.update(r + 1, neg * static_cast<T>(r + 1));
690 }
691 }
692
697 void point_update(const size_t i, const T & delta)
698 {
699 update(i, i, delta);
700 }
701
708 T prefix(const size_t i) const
709 {
711 << "Range_Fenwick_Tree::prefix: index " << i << " >= size " << n;
712
713 return prefix_sum(i);
714 }
715
723 T query(const size_t l, const size_t r) const
724 {
726 << "Range_Fenwick_Tree::query: r=" << r << " >= n=" << n;
728 << "Range_Fenwick_Tree::query: l=" << l << " > r=" << r;
729
730 return l > 0 ? prefix_sum(r) - prefix_sum(l - 1) : prefix_sum(r);
731 }
732
737 T get(const size_t i) const
738 {
739 return query(i, i);
740 }
741
746 void set(const size_t i, const T & value)
747 {
748 point_update(i, value - get(i));
749 }
750
752 [[nodiscard]] constexpr size_t size() const noexcept { return n; }
753
755 [[nodiscard]] constexpr bool is_empty() const noexcept { return n == 0; }
756
762 {
763 auto ret = Array<T>::create(n);
764 for (size_t i = 0; i < n; ++i)
765 ret(i) = get(i);
766 return ret;
767 }
768
770 void swap(Range_Fenwick_Tree & other) noexcept
771 {
772 b1.swap(other.b1);
773 b2.swap(other.b2);
774 std::swap(n, other.n);
775 }
776 };
777} // end namespace Aleph
778
779# endif /* TPL_FENWICK_TREE_H */
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
Standard functor implementations and comparison objects.
size_t size_t int32_t value
Definition ca-c-api.h:116
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Fenwick tree over an arbitrary abelian group.
void fill_from_std_iter(StdIt first, StdIt last)
Fill the internal storage from a standard iterator range and build.
Array< T > values() const
Reconstruct all original values into an Array.
T query(const size_t l, const size_t r) const
Range query: Plus(a[l], a[l+1], ..., a[r]).
constexpr bool is_empty() const noexcept
True if the tree contains no elements.
Gen_Fenwick_Tree(const DynList< T > &values, Plus pop=Plus(), Minus mop=Minus())
Construct from a DynList<T> in O(n) time.
void set(const size_t i, const T &value)
Set a[i] = value.
void fill_from_aleph_it(AlephIt it)
Fill the internal storage from an Aleph-style iterator (get_it()) and build.
void swap_operations(Gen_Fenwick_Tree &other)
T prefix(size_t i) const
Prefix query: Plus(a[0], a[1], ..., a[i]).
void update(size_t i, const T &delta)
Point update: a[i] = Plus(a[i], delta).
T get(const size_t i) const
Retrieve the logical value a[i].
void build()
O(n) bottom-up construction of the tree array from raw values already placed in tree[1....
Gen_Fenwick_Tree(const size_t num, Plus pop=Plus(), Minus mop=Minus())
Construct a tree with num elements, all equal to the identity T().
Gen_Fenwick_Tree(Gen_Fenwick_Tree &&other) noexcept(std::is_nothrow_move_constructible_v< Plus > and std::is_nothrow_move_constructible_v< Minus >)
Take the elements of another tree, which is left empty.
static constexpr size_t lowbit(size_t x) noexcept
Return the least significant set bit of x (as a mask).
void fill_from_indexed(F getter)
Fill the internal storage from a 0-based indexed getter and build.
T Item_Type
The type of element stored in the tree.
Gen_Fenwick_Tree(const Array< T > &values, Plus pop=Plus(), Minus mop=Minus())
Construct from an Array<T> in O(n) time.
Gen_Fenwick_Tree(std::initializer_list< T > il, Plus pop=Plus(), Minus mop=Minus())
Construct from an initializer list in O(n) time.
Gen_Fenwick_Tree & operator=(Gen_Fenwick_Tree &&other) noexcept(noexcept(swap(other)))
Exchange this tree with another, which is left with the previous elements of this one.
Gen_Fenwick_Tree(const std::vector< T > &values, Plus pop=Plus(), Minus mop=Minus())
Construct from a std::vector<T> in O(n) time.
void swap(Gen_Fenwick_Tree &other) noexcept(std::is_nothrow_swappable_v< Plus > and std::is_nothrow_swappable_v< Minus >)
Swap this tree with other in O(1).
Gen_Fenwick_Tree(const Gen_Fenwick_Tree &other)=default
Copy another tree: its array, its size and its operations.
Gen_Fenwick_Tree & operator=(const Gen_Fenwick_Tree &other)=default
Copy another tree into this one: its array, its size and its operations.
constexpr size_t size() const noexcept
Number of logical elements.
Fenwick tree supporting range updates and range queries.
Gen_Fenwick_Tree< T > b2
void build_from_diffs(const Array< T > &d)
Rebuild b1 and b2 from a difference array stored in d.
void point_update(const size_t i, const T &delta)
Point update: add delta to a[i].
Range_Fenwick_Tree & operator=(const Range_Fenwick_Tree &other)=default
Copy another tree into this one: its two inner trees and its size.
Range_Fenwick_Tree(const size_t num)
Construct a tree with num elements, all zero.
void update(size_t l, const size_t r, const T &delta)
Range update: add delta to every a[i] with l <= i <= r.
constexpr bool is_empty() const noexcept
True if the tree contains no elements.
void swap(Range_Fenwick_Tree &other) noexcept
Swap this tree with other in O(1).
T get(const size_t i) const
Retrieve the logical value a[i].
Range_Fenwick_Tree(Range_Fenwick_Tree &&other) noexcept
Take the elements of another tree, which is left empty.
void set(const size_t i, const T &value)
Set a[i] = value.
Range_Fenwick_Tree(const Array< T > &values)
Construct from an Array<T> in O(n) time.
Range_Fenwick_Tree(std::initializer_list< T > il)
Construct from an initializer list in O(n) time.
Array< T > values() const
Reconstruct all original values into an Array.
T prefix(const size_t i) const
Prefix query: sum of a[0..i].
Gen_Fenwick_Tree< T > b1
constexpr size_t size() const noexcept
Number of logical elements.
Range_Fenwick_Tree & operator=(Range_Fenwick_Tree &&other) noexcept
Exchange this tree with another, which is left with the previous elements of this one.
Range_Fenwick_Tree(const Range_Fenwick_Tree &other)=default
Copy another tree: its two inner trees and its size.
T query(const size_t l, const size_t r) const
Range query: sum of a[l..r].
T prefix_sum(size_t i) const
Internal: prefix sum P(i) = (i+1)*B1.prefix(i) - B2.prefix(i)
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
A binary functor closed over T.
Arithmetic domain accepted by Fenwick specializations.
Binary operation compatible with Fenwick tree group functors.
Main namespace for Aleph-w library functions.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
static void prefix(Node *root, DynList< Node * > &acc)
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
STL namespace.
Fenwick tree for arithmetic types with find_kth support.
size_t find_kth(T k) const
Find the smallest 0-based index i such that prefix(i) >= k.
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Alias for htlist.H (DynList implementation).
DynList< int > l