-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_11279.kt
52 lines (49 loc) · 1.33 KB
/
main_11279.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
fun main() {
val n = readLine()!!.toInt()
val pq = PriorityQue()
for (i in 1..n) {
val input = readLine()!!.toInt()
if (input == 0)
println(pq.remove())
else
pq.add(input)
}
}
class PriorityQue{
private val list = mutableListOf<Int>()
fun add(input: Int) {
list.add(input)
var prev = list.lastIndex
var pos = (list.lastIndex - 1) / 2
while (pos >= 0) {
if (list[pos] < list[prev]) {
val tem = list[pos]
list[pos] = list[prev]
list[prev] = tem
prev = pos
pos = (pos - 1) / 2
} else break
}
}
fun remove(): Int {
when (list.size) {
0 -> return 0
1 -> return list.removeLast()
}
val ans = list[0]
list[0] = list.removeLast()
var pos = 1
var prev = 0
while (pos <= list.lastIndex) {
val maxPos = if (list[pos] < list.elementAtOrNull(pos + 1) ?: 0) pos + 1 else pos
if (list[maxPos] > list[prev]) {
val tem = list[maxPos]
list[maxPos] = list[prev]
list[prev] = tem
prev = maxPos
pos = maxPos * 2 + 1
} else break
}
return ans
}
}