Created
September 10, 2020 10:51
-
-
Save yh1224/63c1d61ddf619d06028a03f82f4b5184 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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