-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path1993-operations-on-tree.java
79 lines (64 loc) · 1.83 KB
/
1993-operations-on-tree.java
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
class Solution {
private final int[] parent;
private final int[] locked;
private final Map<Integer, List<Integer>> child;
public LockingTree(int[] parent) {
this.parent = parent;
locked = new int[parent.length];
child = new HashMap<>();
for (int i = 0; i < parent.length; i++) {
child.putIfAbsent(parent[i], new ArrayList<>());
child.putIfAbsent(i, new ArrayList<>());
child.get(parent[i]).add(i);
}
}
public boolean lock(int num, int user) {
if (locked[num] <= 0) {
locked[num] = user;
return true;
}
return false;
}
public boolean unlock(int num, int user) {
if (locked[num] == user) {
locked[num] = 0;
return true;
}
return false;
}
public boolean upgrade(int num, int user) {
if (!noneAncestorsLocked(num)) {
return false;
}
int lockedCount = checkDescendantsAndLockIfNeeded(num);
if (lockedCount > 0) {
locked[num] = user;
}
return lockedCount > 0;
}
private boolean noneAncestorsLocked(int num) {
while (num != -1) {
if (locked[num] != 0) {
return false;
}
num = parent[num];
}
return true;
}
private int checkDescendantsAndLockIfNeeded(int num) {
int lockedCount = 0;
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(num);
while (!deque.isEmpty()) {
int n = deque.pollLast();
if (locked[n] > 0) {
lockedCount++;
locked[n] = 0;
}
for (Integer i : child.get(n)) {
deque.addFirst(i);
}
}
return lockedCount;
}
}