-
Notifications
You must be signed in to change notification settings - Fork 522
/
Treap.kt
104 lines (94 loc) · 2.9 KB
/
Treap.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import java.util.Random
import java.util.TreeSet
// https://en.wikipedia.org/wiki/Treap
object Treap {
val random = Random()
data class Treap(
val key: Int,
var left: Treap? = null,
var right: Treap? = null,
var size: Int = 1,
val prio: Long = random.nextLong()
) {
fun update() {
size = 1 + getSize(left) + getSize(right)
}
}
fun getSize(root: Treap?) = root?.size ?: 0
fun split(root: Treap?, minRight: Int): Pair<Treap?, Treap?> {
if (root == null)
return Pair(null, null)
if (root.key >= minRight) {
val leftSplit = split(root.left, minRight)
root.left = leftSplit.second
root.update()
return Pair(leftSplit.first, root)
} else {
val rightSplit = split(root.right, minRight)
root.right = rightSplit.first
root.update()
return Pair(root, rightSplit.second)
}
}
fun merge(left: Treap?, right: Treap?): Treap? {
if (left == null)
return right
if (right == null)
return left
if (left.prio > right.prio) {
left.right = merge(left.right, right)
left.update()
return left
} else {
right.left = merge(left, right.left)
right.update()
return right
}
}
fun insert(root: Treap?, key: Int): Treap? {
val t = split(root, key)
return merge(merge(t.first, Treap(key)), t.second)
}
fun remove(root: Treap?, key: Int): Treap? {
val t = split(root, key)
return merge(t.first, split(t.second, key + 1).second)
}
fun kth(root: Treap, k: Int): Int {
if (k < getSize(root.left))
return kth(root.left!!, k)
else if (k > getSize(root.left))
return kth(root.right!!, k - getSize(root.left) - 1)
return root.key
}
fun print(root: Treap?) {
if (root == null)
return
print(root.left)
println(root.key)
print(root.right)
}
// random test
@JvmStatic
fun main(args: Array<String>) {
val time = System.currentTimeMillis()
var treap: Treap? = null
val set = TreeSet<Int>()
for (i in 0..999999) {
val key = random.nextInt(100000)
if (random.nextBoolean()) {
treap = remove(treap, key)
set.remove(key)
} else if (!set.contains(key)) {
treap = insert(treap, key)
set.add(key)
}
if (set.size != getSize(treap))
throw RuntimeException()
}
for (i in 0 until getSize(treap)) {
if (!set.contains(kth(treap!!, i)))
throw RuntimeException()
}
println(System.currentTimeMillis() - time)
}
}