-
Notifications
You must be signed in to change notification settings - Fork 522
/
FenwickTree.kt
58 lines (51 loc) · 1.22 KB
/
FenwickTree.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
object FenwickTree {
// T[pos] += value
fun add(t: IntArray, pos: Int, value: Int) {
var i = pos
while (i < t.size) {
t[i] += value
i = i or i + 1
}
}
// sum[0..pos]
fun sum(t: IntArray, pos: Int): Int {
var res = 0
var i = pos
while (i >= 0) {
res += t[i]
i = (i and i + 1) - 1
}
return res
}
///////////////////////////////////////////////////
// T[pos] = max(T[pos], value)
fun set(t: IntArray, pos: Int, value: Int) {
var i = pos
while (i < t.size) {
t[i] = maxOf(t[i], value)
i = i or i + 1
}
}
// max[0..pos]
fun max(t: IntArray, pos: Int): Int {
var i = pos
var res = Int.MIN_VALUE
while (i >= 0) {
res = maxOf(res, t[i])
i = (i and i + 1) - 1
}
return res
}
// Usage example
@JvmStatic
fun main(args: Array<String>) {
val t1 = IntArray(10)
add(t1, 0, 1)
add(t1, 9, -2)
println(-1 == sum(t1, 9))
val t2 = IntArray(10)
set(t2, 0, 3)
set(t2, 3, 2)
println(3 == max(t2, 9))
}
}