-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1993-operations-on-tree.kt
53 lines (45 loc) · 1.24 KB
/
1993-operations-on-tree.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
class LockingTree(val parent: IntArray) {
val locked = IntArray (parent.size) { -1 }
val child = HashMap<Int, MutableList<Int>>()
init {
for (i in 1 until parent.size) {
child[parent[i]] = child.getOrDefault(parent[i], mutableListOf<Int>()).apply { add(i) }
}
}
fun lock(num: Int, user: Int): Boolean {
if (locked[num] != -1)
return false
locked[num] = user
return true
}
fun unlock(num: Int, user: Int): Boolean {
if (locked[num] != user)
return false
locked[num] = -1
return true
}
fun upgrade(num: Int, user: Int): Boolean {
var i = num
while (i != -1) {
if (locked[i] != -1)
return false
i = parent[i]
}
var lockedCount = 0
var q = LinkedList<Int>()
q.add(num)
while (q.isNotEmpty()) {
var n = q.removeLast()
if (locked[n] != -1) {
locked[n] = -1
lockedCount++
}
child[n]?.forEach {
q.addFirst(it)
}
}
if (lockedCount > 0)
locked[num] = user
return lockedCount > 0
}
}