Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
binary_indexed_tree.h
Go to the documentation of this file.
1// Copyright 2010-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14#ifndef OR_TOOLS_ALGORITHMS_BINARY_INDEXED_TREE_H_
15#define OR_TOOLS_ALGORITHMS_BINARY_INDEXED_TREE_H_
16
17#include <vector>
18
19#include "absl/log/check.h"
20
22
23// A binary indexed tree is a data structure that represents an array of
24// numbers and supports two operations:
25// 1) add a number to i-th element of the array.
26// 2) find the sum of a prefix of the array (elements from 0-th to j-th).
27// See http://en.wikipedia.org/wiki/Fenwick_tree.
28template <typename T>
30 public:
31 // Initializes the storage for a binary indexed tree of a given size. The
32 // tree contains all zeros initially.
33 explicit BinaryIndexedTree(int n) : tree_(n + 1, 0) {}
34
35 // Adds value to index-th number.
36 void AddItem(int index, T value) {
37 DCHECK_GE(index, 0);
38 DCHECK_LT(index, tree_.size() - 1);
39 // Internal indices of BinaryIndexedTree are 1 based.
40 ++index;
41 while (index < tree_.size()) {
42 tree_[index] += value;
43 index += index & -index;
44 }
45 }
46
47 // Finds the sum of a prefix [0, index]. Passing index == -1 is allowed,
48 // will return 0 in that case.
49 T GetPrefixSum(int index) const {
50 DCHECK_GE(index, -1);
51 DCHECK_LT(index + 1, tree_.size());
52 // Internal indices of BinaryIndexedTree are 1 based.
53 ++index;
54 T prefix_sum = 0;
55 while (index > 0) {
56 prefix_sum += tree_[index];
57 index -= index & -index;
58 }
59 return prefix_sum;
60 }
61
62 // Returns the size of the tree.
63 int size() const { return tree_.size() - 1; }
64
65 private:
66 std::vector<T> tree_;
67};
68
69} // namespace operations_research
70
71#endif // OR_TOOLS_ALGORITHMS_BINARY_INDEXED_TREE_H_
int size() const
Returns the size of the tree.
void AddItem(int index, T value)
Adds value to index-th number.
int64_t value
int index
In SWIG mode, we don't want anything besides these top-level includes.