Skip to content

Instantly share code, notes, and snippets.

@dimitrilw
Created July 31, 2023 22:48
Show Gist options
  • Save dimitrilw/58a85c05ceeba7a7c57f2f098c6f8422 to your computer and use it in GitHub Desktop.
Save dimitrilw/58a85c05ceeba7a7c57f2f098c6f8422 to your computer and use it in GitHub Desktop.
Fenwick tree
// https://en.wikipedia.org/wiki/Fenwick_tree
// https://www.youtube.com/watch?v=uSFzHCZ4E-8
type FenwickTree []int
// returns sum of all elements up to index 'i'
func (ft FenwickTree) sum(i int) int {
res := 0
for ; i > 0; i -= lsb(i) {
res += ft[i]
}
return res
}
// adds value 'n' to index 'i' and propogates updates across the Fenwick Tree
func (ft FenwickTree) add(i, n int) {
for ; i < len(ft); i += lsb(i) {
ft[i] += n
}
}
// least significant bit / last set bit; used by FenwickTree
func lsb(n int) int { return n & (-n) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment