Skip to content

Instantly share code, notes, and snippets.

@yh1224
Created September 10, 2020 10:51
Show Gist options
  • Save yh1224/63c1d61ddf619d06028a03f82f4b5184 to your computer and use it in GitHub Desktop.
Save yh1224/63c1d61ddf619d06028a03f82f4b5184 to your computer and use it in GitHub Desktop.
package lib
class FenwickTree(private val n: Int = 0) {
private val data = LongArray(n)
fun add(p: Int, x: Long) {
var pp = p + 1
while (pp <= n) {
data[pp - 1] += x
pp += pp and -pp
}
}
fun sum(l: Int, r: Int): Long = sum(r) - sum(l)
private fun sum(r: Int): Long {
var s = 0L
var rr = r
while (rr > 0) {
s += data[rr - 1]
rr -= rr and -rr
}
return s
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment