Created
July 31, 2023 22:48
-
-
Save dimitrilw/58a85c05ceeba7a7c57f2f098c6f8422 to your computer and use it in GitHub Desktop.
Fenwick tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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