forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPersistentTree.kt
More file actions
54 lines (46 loc) · 1.66 KB
/
Copy pathPersistentTree.kt
File metadata and controls
54 lines (46 loc) · 1.66 KB
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
package structures
import numeric.FFT
import optimization.Simplex
// https://en.wikipedia.org/wiki/Persistent_data_structure
object PersistentTree {
fun build(left: Int, right: Int): Node {
if (left == right) return Node(0)
val mid = left + right shr 1
return Node(build(left, mid), build(mid + 1, right))
}
fun sum(from: Int, to: Int, root: Node?, left: Int, right: Int): Int {
if (from > right || left > to) return 0
if (from <= left && right <= to) return root!!.sum
val mid = left + right shr 1
return sum(from, to, root!!.left, left, mid) + sum(from, to, root.right, mid + 1, right)
}
operator fun set(pos: Int, value: Int, root: Node?, left: Int, right: Int): Node {
if (left == right) return Node(value)
val mid = left + right shr 1
return if (pos <= mid) Node(set(pos, value, root!!.left, left, mid), root.right) else Node(
root!!.left, set(pos, value, root.right, mid + 1, right)
)
}
// Usage example
fun main(args: Array<String?>?) {
val n = 10
val t1 = build(0, n - 1)
val t2 = set(0, 1, t1, 0, n - 1)
System.out.println(0 == sum(0, 9, t1, 0, n - 1))
System.out.println(1 == sum(0, 9, t2, 0, n - 1))
}
class Node {
var left: Node? = null
var right: Node? = null
var sum = 0
internal constructor(value: Int) {
sum = value
}
internal constructor(left: Node?, right: Node?) {
this.left = left
this.right = right
if (left != null) sum += left.sum
if (right != null) sum += right.sum
}
}
}