Skip to content

Instantly share code, notes, and snippets.

@dyguests
Created November 18, 2021 07:53
Show Gist options
  • Save dyguests/eb0f86f3a72fceb66e35c9bd3fa3f446 to your computer and use it in GitHub Desktop.
Save dyguests/eb0f86f3a72fceb66e35c9bd3fa3f446 to your computer and use it in GitHub Desktop.
BinaryIndexedTree, 数状数组
class BinaryIndexedTree(private var nums: IntArray) {
var size: Int = nums.size
private val _bit = IntArray(size + 1)
init {
for (i in 0 until size) init(i, nums[i])
}
private fun init(index: Int, value: Int) {
var i = index + 1
while (i <= size) {
_bit[i] += value
i += i and -i
}
}
fun update(index: Int, value: Int) {
val diff = value - nums[index]
nums[index] = value
init(index, diff)
}
fun sum(i: Int): Int {
var i = i
var sum = 0
i++
while (i > 0) {
sum += _bit[i]
i -= i and -i
}
return sum
}
fun sum(i: Int, j: Int): Int {
return sum(j) - sum(i - 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment