NewFenwickTree creates a new Fenwick tree, initializes bit with the values of the array. Note that the queries and updates should have one based indexing.
(array []int)
| 18 | // the values of the array. Note that the queries and updates should have |
| 19 | // one based indexing. |
| 20 | func NewFenwickTree(array []int) *FenwickTree { |
| 21 | newArray := []int{0} // Appending a 0 to the beginning as this implementation uses 1 based indexing |
| 22 | fenwickTree := &FenwickTree{ |
| 23 | n: len(array), |
| 24 | array: append(newArray, array...), |
| 25 | bit: append(newArray, array...), |
| 26 | } |
| 27 | for i := 1; i < fenwickTree.n; i++ { |
| 28 | nextPos := i + (i & -i) |
| 29 | if nextPos <= fenwickTree.n { |
| 30 | fenwickTree.bit[nextPos] += fenwickTree.bit[i] |
| 31 | } |
| 32 | } |
| 33 | return fenwickTree |
| 34 | } |
| 35 | |
| 36 | // PrefixSum returns the sum of the prefix ending at position pos. |
| 37 | func (f *FenwickTree) PrefixSum(pos int) int { |
no outgoing calls