Debian Codegraph @

dwsys/BinaryIndexedTree.h

raw
1 #ifndef _BinaryIndexedTree_h_
2 #define _BinaryIndexedTree_h_
3 /* BinaryIndexedTree.h
4 *
5 * Copyright (C) 2025 David Weenink
6 *
7 * This code is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or (at
10 * your option) any later version.
11 *
12 * This code is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this work. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "melder.h"
22
23 class BinaryIndexedTree {
24 private:
25 autoINTVEC bit;
26 public:
27
28 BinaryIndexedTree () { }
29
30 BinaryIndexedTree (integer size) {
31 bit = zero_INTVEC (size);
32 }
33
34 /*
35 This elegant initialization in O(n) time I found at sdnr1's blog at
36 https://codeforces.com/blog/entry/63064
37 */
38 BinaryIndexedTree (constINTVEC const& v) {
39 Melder_assert (v.size > 0);
40 bit = zero_INTVEC (v.size);
41 for (integer i = 1; i <= v.size; i ++) {
42 bit [i] += v [i];
43 const integer next = i + (i & -i);
44 if (next <= v.size)
45 bit [next] += bit [i];
46 }
47 }
48
49 // update bit if we put a new 'value' at 'index'
50 void update (integer index, integer value) {
51 Melder_assert (index <= bit.size);
52 for (integer i = index; i <= bit.size; i += i & -i)
53 bit [i] += value;
54 }
55
56 integer query (integer index) {
57 Melder_assert (index <= bit.size);
58 integer sum = 0;
59 for (integer i = index; i >= 1; i -= i & -i)
60 sum += bit [i];
61 return sum;
62 }
63
64 integer queryRange (integer left, integer right) {
65 Melder_assert (left <= right);
66 return query (right) - query (left - 1);
67 }
68 };
69
70
71 #endif /* _BinaryIndexedTree_h_ */